如果我有一个实体Person
包含一些惰性集合(Cars
,Bills
,Friends
,...),并且想要编写一个JpaRepository方法,给了我所有热切期待的人Cars
,这可能吗?
我知道人们可以在单个物体上做到这一点,但是对于人物集合来说这是否可行?
答案 0 :(得分:5)
是的,Spring Data JPA提供了一个非常方便的@EntityGraph
注释。它可用于微调查询的已使用实体图。每个JPA查询都使用一个隐式实体图,它指定根据关系fetchtype设置急切或延迟获取哪些元素。如果您想要急切地获取特定关系,则需要在实体图中指定它。
@Repository
public interface PersonRepository extends CrudRepository<Person, Long> {
@EntityGraph(attributePaths = { "cars" })
Person getByName(String name);
}
答案 1 :(得分:1)
使用以下JPA查询获取两个表数据。这里使用jpa查询来获取汽车。
“fetch”连接允许使用单个select来初始化值的关联或集合及其父对象。这在集合的情况下特别有用。它有效地覆盖了关联和集合的映射文件的外连接和延迟声明。
的更多说明,请参阅此处使用“加入获取”来热切地获取对象。
public interface CustomRepository extends JpaRepository<Person, Long> {
@Query("select person from PersonModel as person left join fetch person.cars as cars")
public PersonModel getPersons();
}