Java 即使fetchtype是惰性的,JPA也会加载太多数据
我有一个应用程序,加载与下水道网络相关的数据。这里是一个涉及实体的示例。首先,我定义一个Java 即使fetchtype是惰性的,JPA也会加载太多数据,java,hibernate,jpa,Java,Hibernate,Jpa,我有一个应用程序,加载与下水道网络相关的数据。这里是一个涉及实体的示例。首先,我定义一个网络实体: @Entity @Table(name = "network") public class Network extends Serializable { @Id @generatedValue(strategy=GenerationType.AUTO) private Long id; ... @OneToMany(mappedBy = "network") privat
网络实体:
@Entity
@Table(name = "network")
public class Network extends Serializable {
@Id
@generatedValue(strategy=GenerationType.AUTO)
private Long id;
...
@OneToMany(mappedBy = "network")
private List<Conduit> conduits;
@OneToMany(mappedBy = "network")
private List<ConduitVolumeter> conduitVolumeters;
...
}
接下来,我定义ConduitVolumeter
。这表示用于测量导管中体积的测量设备。由于可以在其他网络项目中测量体积,因此数据库中有一个与Volumeter
表关联的抽象类Volumeter
@Entity(name = "ConduitVolumeter")
@DiscriminatorValue("1")
public class ConduitVolumeter extends Volumeter {
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "id_nme")
private Conduit conduit;
...
}
@Entity
@Table(name = "volumeter")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "nme_type", discriminatorType = DiscriminatorType.INTEGER)
public abstract class Volumeter extends Serializable {
@Id
@generatedValue(strategy=GenerationType.AUTO)
private Long id;
...
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "id_network", nullable = false)
private Network network;
...
}
问题是,当我尝试加载与网络关联的所有导管时,Hibernate会根据其日志,系统地加载与每个已加载导管关联的每个体积计,一次加载一个
Hibernate:
select
conduit0_.id as id_1_7_,
conduit0_.name as name23_7_,
conduit0_.id_network as id_netw39_7_,
from
conduit conduit0_ cross
join
network network1_
where
conduit0_.id_network=?
我的问题:为什么Hibernate尝试加载volumeter数据?每个@ManyToOne
和@OneToOne
注释都设置了FetchType.LAZY
。我错过了什么
顺便说一句,我被要求在遗留数据库中使用JPA。数据库模型是问题所在吗?有没有办法在不使用容量计的情况下加载导管
问候
弗朗索瓦FetchType只是一个提示。这取决于您查询数据的方式,如果您使用的是spring数据jpa存储库方法,如findOne或findBy方法(派生查询),那么Lazy应该可以工作,但是如果您使用jpa存储库和@Query on repository方法并编写查询,那么Lazy可能无法工作。请始终记住,Lazy fetch是一个提示,不一定。谢谢你的回答。我试试看。实际上,我正在导管存储库中使用查询。我将尝试使用findBy方法之一来验证您的答案。我尝试使用管道存储库中的spring jpa数据存储库方法findByNetwork。没有什么变化。它像以前一样加载容量计。
Hibernate:
select
conduit0_.id as id_1_7_,
conduit0_.name as name23_7_,
conduit0_.id_network as id_netw39_7_,
from
conduit conduit0_ cross
join
network network1_
where
conduit0_.id_network=?
Hibernate:
select
conduitvol0_.id as id2_116_0_,
conduitvol0_.name as name10_116_0_,
conduitvol0_.id_network as id_netw15_116_0_,
conduitvol0_.id_nme as id_nme17_116_0_
from
volumeter conduitvol0_
where
conduitvol0_.id_nme=?
and conduitvol0_.nme_type=1