我使用开放式JDK 11,JPA 2.1和Hibernate Core 5.4.0.Final。我有一个具有许多子关联的实体Ave
,其中Bid
和Buyer
。基数是:
1 Ave : Many Bid
1 Ave : Many Buyer
这是Ave
实体的源代码的摘录:
@Entity
@Table(name = "ave")
@Access(AccessType.FIELD)
public class Ave implements Serializable, SearchableEntity {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@Column(name = "id", updatable = false, nullable = false)
private int id;
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.MERGE, targetEntity = Buyer.class)
@JoinColumn(name = "ave_id")
@Fetch(value = FetchMode.JOIN)
private Set<Buyer> allPotentialBuyers = new LinkedHashSet<>();
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, targetEntity = Bid.class)
@JoinColumn(name = "ave_id")
@Fetch(value = FetchMode.JOIN)
private Set<Bid> bids = new HashSet<>();
// ... more code here ....
}
当我执行JPA查询时
Query query2 = this.em.createQuery(" select ave from Ave ave where ave.id =16 ");
query2.getResultList();
休眠执行3(三个)SQL查询,尽管我既不希望获取关联的Bid
也不要获取Buyer
:
1。)首先查询-提取Ave
实体-确定:
04:34:15,717 INFO [stdout] (default task-2) Hibernate: select ave0_.id as id1_0_, ave0_.angebotType as angebotT2_0_, ave0_.bidStep as bidStep3_0_, ave0_.bidwinner_id as bidwinne7_0_, ave0_.endDate as endDate4_0_, ave0_.home_id as home_id8_0_, ave0_.user_id as user_id5_0_, ave0_.startDate as startDat6_0_, ave0_.vertragsErrichter_id as vertrags9_0_ from ave ave0_ where ave0_.id=16
2。)Secodn查询-获取关联的Bid
-为什么?我不想要!:
04:34:15,928 INFO [stdout] (default task-2) Hibernate: select bids0_.ave_id as ave_id3_4_0_, bids0_.id as id1_4_0_, bids0_.id as id1_4_1_, bids0_.abgabeDatum as abgabeDa2_4_1_, bids0_.ave_id as ave_id3_4_1_, bids0_.bidmaker_id as bidmaker6_4_1_, bids0_.bidPrice as bidPrice4_4_1_, bids0_.status as status5_4_1_, bids0_.vtgerrichter_id as vtgerric7_4_1_ from bid bids0_ where bids0_.ave_id=?
3。)第三个查询-获取关联的Buyer
-为什么?我不要:
04:34:16,082 INFO [stdout] (default task-2) Hibernate: select allpotenti0_.ave_id as ave_id2_5_0_, allpotenti0_.id as id1_5_0_, allpotenti0_.id as id1_5_1_, allpotenti0_.ave_id as ave_id2_5_1_, allpotenti0_.contact_id as contact_3_5_1_, allpotenti0_.idx as idx4_5_1_, allpotenti0_.main_buyer_id as main_buy5_5_1_ from buyer allpotenti0_ where allpotenti0_.ave_id=?
@Fetch(FetchMode.JOIN)
覆盖您定义的FetchType.LAZY
。这使您的协会热切地加载而不是懒惰。因此,
FetchMode.JOIN
在获取实体时非常有用直接通过其标识符或自然ID。此外,
FetchMode.JOIN
充当FetchType.EAGER策略。即使我们将关联标记为FetchType.LAZY
,FetchMode.JOIN
急切地加载协会。