Java 如何在spring数据中使用crudepository强制加载?
我有一个实体,其中包含一个Java 如何在spring数据中使用crudepository强制加载?,java,spring,hibernate,spring-data,Java,Spring,Hibernate,Spring Data,我有一个实体,其中包含一个列表,因此默认情况下该列表是惰性的: interface MyEntityRepository extends CrudRepository<MyEntity, Long> { } @Entity public class MyEntity { @Id private Long id; @OneToMany(mappedBy = "bar") //lazy by default private List<Bar&g
列表
,因此默认情况下该列表是惰性的
:
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
}
接口MyEntityRepository扩展了CrudRepository{
}
@实体
公共类MyEntity{
@身份证
私人长id;
@OneToMany(mappedBy=“bar”)//默认情况下是懒惰的
私人酒吧名单;
}
@实体
公共类酒吧{
//更多
}
问题:在执行
repository.findOne(id)
时,我如何强制进行即时加载?我也需要这个,当我在事务中的服务对象中调用dao时,我调用get方法,这样就不会出现异常,我就能够获取记录。
类似于java 8:
public ProductEntity findProduct(int id) {
ProductEntity p = productRepository.findOne(id);
p.getPresentations().stream().count();
return p;
}
p.getPresentations().stream().count()
将强制提取,我知道这不是一种干净的方法,但它可以同时完成任务您可以强制使用左连接提取编写自定义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)
}
接口MyEntityRepository扩展了CrudRepository{
@查询(“从MyEntity e中选择e left join fetch e.bar b,其中e.id=?1”)
MyEntity findOne(长id)
}
从
@OneToMany(mappedBy = "bar") //lazy by default
到
findallbyd()使用即时获取,无需自定义
interface MyEntityRepository extends CrudRepository<MyEntity, Long> {
Optional<MyEntity> findAllById(long id);
}
接口MyEntityRepository扩展了Crudepository{
可选findAllById(长id);
}
@OneToMany(fetch=FetchType.EAGER)
这会有帮助吗?我知道我可以像这样强制执行EAGER
模式。但是我想坚持使用默认的lazy
并在一个特定的select上强制所有列表都使用eager。那么,如果您在DAO中使用criteria,您可以通过criteria.setFetchMode(“bar”,FetchMode.eager)
强制获取类型,或者您可以使用MyEntity p=(MyEntity)sess.get(MyEntity.class,id);初始化(p.getBars())代码>这就意味着要写我自己的标准。总的来说,这很好,但我希望spring数据会带来一些东西。引用我自己的话:“我知道我可以像这样强制使用渴望模式。但我想坚持惰性默认值,只强制使用渴望[…]一个特定的选择”此解决方案生成多个查询。您能显示源代码吗?我认为芬德比和芬达尔比没有任何区别。
interface MyEntityRepository extends CrudRepository<MyEntity, Long> {
Optional<MyEntity> findAllById(long id);
}