代码之家  ›  专栏  ›  技术社区  ›  Alex Mi

Hibernate获取子实体,尽管它不应该

  •  0
  • Alex Mi  · 技术社区  · 6 年前

    我使用开放的JDK 11、JPA 2.1和Hibernate Core 5.4.0.Final。 我有一个实体 Ave 有很多儿童协会,其中 Bid Buyer . 基数为:

    1 Ave : Many Bid
    
    1 Ave : Many Buyer
    

    这是源代码的摘录 大道 实体:

    @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();
    

    hibernate执行3(三)个SQL查询,但我不想获取相关的 投标 也没有 买方 :

    1.)FIRST查询-获取 大道 实体-好:

    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查询-获取相关联的 投标 为什么?我不想要!:

    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.)第三个查询-获取相关联的 买方 为什么?我不想:

    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=?
    
    0 回复  |  直到 6 年前
        1
  •  2
  •   Andronicus    6 年前
    1. Hibernate 5.3+是JPA 2.2标准。
    2. 您的Fetch策略- @Fetch(FetchMode.JOIN) 覆盖 FetchType.LAZY 你定义。这会让你的关联加载得很快 而不是懒散。

    https://docs.jboss.org/hibernate/stable/orm/userguide/html_single/Hibernate_User_Guide.html#fetching-fetchmode-join

    因此, FetchMode.JOIN 在获取实体时非常有用 直接通过它们的标识符或natural-id。

    此外 获取模式。加入 充当FetchType。EAGER战略。即使 我们将该协会标记为 获取类型。懒惰 ,the 获取模式。加入 将 急切地加载协会。