【问题标题】:spring data jpa @EntityGraph method with Collection result throws BeanCreationExceptionspring data jpa @EntityGraph 方法与 Collection 结果抛出 BeanCreationException
【发布时间】:2019-01-31 20:59:32
【问题描述】:

嵌套异常是 org.springframework.beans.factory.BeanCreationException:创建名为“cityDao”的 bean 时出错:调用 init 方法失败;嵌套异常是 java.lang.IllegalArgumentException:无法为方法 public abstract java.util.List com.server.repository.location.CityDao.findAllWithCountry() 创建查询!没有找到类型 City 的属性 findAllWithCountry!

@Transactional
public interface CityDao extends JpaRepository<City, Integer> {
    @EntityGraph(attributePaths = "country")
    List<City> findAllWithCountry(); //this one does not work

    @EntityGraph(attributePaths = "country")
    City findOneWithCountryById(int id); //this one works
}

实体:

@Entity
@Table(name = "city", uniqueConstraints = {
        @UniqueConstraint(columnNames = {"country", "city_name", "latitude", "longitude"})
})
@Data
public class City {
    @ManyToOne(fetch = FetchType.LAZY)
    @NotNull
    @JoinColumn(name = "country")
    private Country country;
}

我正在尝试实现 @EntityGraph 以提高 API 性能。 第一种方法抛出BeanCreationException,而第二种方法正在运行。唯一的区别是第一个返回一个集合,第二个返回一个实体。有办法解决吗?

【问题讨论】:

    标签: hibernate spring-boot spring-data-jpa


    【解决方案1】:

    关键问题不是Citycountry属性,看看stacktrace:

    No property findAllWithCountry found for type City!
    

    这意味着它根本无法派生查询,更不用说找到country 属性了。

    您可以覆盖默认的findAll

    @EntityGraph(attributePaths = "country")
    @Override
    List<City> findAll();
    

    这会将此优化应用于您的所有findAll

    当我过去遇到这种情况时(我希望有多个具有相同查询属性但每个注释不同的派生方法),是编写 customize the base repo 或使用 @Query 编写查询。

    【讨论】:

      猜你喜欢
      • 2014-12-05
      • 1970-01-01
      • 2020-08-18
      • 2016-10-12
      • 1970-01-01
      • 1970-01-01
      • 2018-11-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多