簡體   English   中英

JPA ManyToMany聯接表查詢

[英]JPA ManyToMany join table query

假設這些實體

@Entity
public class EntityNote implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @SequenceGenerator(name="SeqEntityNote", sequenceName="SeqEntityNote", allocationSize = 1)
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="SeqEntityNote")
    private long id;
    private Date date;
    private String subject;
    private String content;

    @ManyToMany
    private List<EntityTopic> listEntityTopic;

    //setters/getters

@Entity
public class EntityTopic implements Serializable {
    @Id
    @SequenceGenerator(name="SeqEntityTopic", sequenceName="SeqEntityTopic", allocationSize = 1)
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="SeqEntityTopic")
    private long id;
    private String name;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

在我的數據庫中,名為“ entity_note_list_entity_topic”的聯接表記錄了ManyToMany關系。

到目前為止,這可以正常工作。

但是我想執行一個計數查詢,例如“每個EntitityTopic有多少個EntityNotes”

不幸的是,我在這種情況下迷失了。

該查詢如何編寫?

我的兩個實體中是否需要其他元素?

(在很多示例中,我在ManyToMany上看到了使用appededBy屬性的反向關系。我需要這個嗎?)

如果使多對多關系成為雙向,這將是最簡單的。 由於它使用相同的db結構,因此不涉及任何嚴重的額外費用,並且列表是延遲加載的,因此,如果不使用該關系,則不會填充列表(您可以通過將訪問器設為私有來隱藏第二個方向)。

只需更改:

@Entity
public class EntityTopic implements Serializable {
  ...
  @ManyToMany(mappedBy="listEntityTopic")
  private List<EntityNote> notes;
}

您可以發出常規計數jpql查詢,例如:

SELECT count(n) from EntityTopic t INNER JOIN t.notes n where t.name =:name

因此,如果不需要,您就不必檢索筆記和主題。

但我也相信您的原始映射也可以是以下查詢:

SELECT COUNT(n) FROM EntityNote n INNER JOIN n.listEntityTopic t WHERE t.name = :name

如果您具有以下代碼:

@Entity
public class EntityNote implements Serializable {
  @ManyToMany(fetch = FetchType.LAZY)
  private List<EntityTopic> topics;
}

@Entity
public class EntityTopic implements Serializable {
  @ManyToMany(fetch = FetchType.LAZY)
  private List<EntityNote> notes;
}

然后, topic.getNotes().size()將為您提供與主題關聯的注釋數。 將Hibernate用作JPA提供程序時,將為此發出SELECT COUNT(...)查詢,而不是加載所有關聯的注釋。 如果這對於您開箱即用而言不起作用,請按照本文的說明將集合標記為特別懶惰。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM