如何在spring-data中强制加载CrudRepository?

时间:2015-08-06 11:38:18

标签: java spring hibernate spring-data

我有一个包含List的实体,因此默认加载lazy

interface MyEntityRepository extends CrudRepository<MyEntity, Long> {

}

@Entity
public class MyEntity {
    @Id
    private Long id;

    @OneToMany(mappedBy = "bar") //lazy by default
    private List<Bar> bars;
}

@Entity
public class Bar {
    //some more
}

问题:执行repository.findOne(id)时如何强行加载?

4 个答案:

答案 0 :(得分:7)

您可以强制使用left join fetch编写自定义HQL查询,例如:

interface MyEntityRepository extends CrudRepository<MyEntity, Long> {
    @Query("select e from MyEntity e left join fetch e.bar b where e.id = ?1")
    MyEntity findOne(long id)
}

答案 1 :(得分:3)

我也需要这个,因为我在一个服务对象里面调用dao,我调用的事务调用get方法,所以没有异常,我能够获取记录。 类似于java 8中的东西:

public ProductEntity findProduct(int id) {
    ProductEntity p = productRepository.findOne(id);
    p.getPresentations().stream().count();
    return p;
}

p.getPresentations().stream().count();将强制取出,我知道这不是一个干净的方法,但它可以在同一时间完成工作

答案 2 :(得分:0)

findAllById()使用预先获取功能,无需自定义。

  interface MyEntityRepository extends CrudRepository<MyEntity, Long> {        
    Optional<MyEntity> findAllById(long id);
}

答案 3 :(得分:-4)

更改映射
@OneToMany(mappedBy = "bar") //lazy by default

@OneToMany(mappedBy = "bar", fetch = FetchType.EAGER) //lazy by default