2017-06-22 72 views
0

如果我有一个实体Person一些懒惰的集合(CarsBillsFriends,...),并希望写一个JpaRepository法,让我所有的人indluding预先抓取Cars,是这可能吗?JpaRepository:取特定的懒惰集合

我知道一个人可以在单个物体上做到这一点,但是这对某些人来说是可能的吗?

+0

[休眠弹簧JPA负载只有特定的懒惰关系](的可能的复制https://stackoverflow.com/questions/40932584/hibernate-spring-jpa-load-only-specific-lazy -关系) – crizzis

回答

1

使用以下JPA查询来获取这两个表数据。这里使用jpa查询来获取汽车。

“提取”连接允许使用单个选择将关联或值集合与其父对象一起初始化。这在收集的情况下特别有用。它有效地覆盖了关联和集合映射文件的外连接和惰性声明。

更多解释见上join fetch

此使用“连接抓取”,获取对象热切。

public interface CustomRepository extends JpaRepository<Person, Long> { 

    @Query("select person from PersonModel as person left join fetch person.cars as cars") 
    public PersonModel getPersons(); 
} 
2

是的,Spring Data JPA提供了非常方便的@EntityGraph注释。它可以用来微调查询中使用的实体图形。每个JPA查询都使用隐式entitygraph,它指定根据关系fetchtype设置,哪些元素是热切或懒惰地获取的。如果你想要一个特定的关系被急切地提取,你需要在entitygraph中指定它。

@Repository 
public interface PersonRepository extends CrudRepository<Person, Long> { 
    @EntityGraph(attributePaths = { "cars" }) 
    Person getByName(String name); 
} 

​​