JPA ManyToMany连接表查询

时间:2015-02-22 10:33:45

标签: java jpa

假设这些实体

@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上看到使用mappedBy属性的反向关系..我需要这个吗?)

2 个答案:

答案 0 :(得分:1)

如果您将多对多关系双向化,那将是最简单的。没有涉及严重的额外成本,因为它使用相同的数据库结构,并且列表是延迟加载的,因此如果未使用关系,则不会填充列表(您可以通过使访问者保持私有来隐藏第二个方向)。

简单地改变:

@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

答案 1 :(得分:0)

如果您有以下代码:

@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(...)查询,而不是加载所有关联的注释。如果这对您来说不起作用,请使用说明in this post将这些集合标记为额外的延迟。