在JPA中,我如何包含" count"我的查询中的子句?

时间:2014-06-18 16:11:03

标签: hibernate jpa jpa-2.0 hibernate-4.x

我正在使用JPA 2.0和Hibernate 4.1.0.Final。我有以下实体:

@Entity
@Table(name = "group")
public class Group    
{
    @Id
    @NotNull
    @GeneratedValue(generator = "uuid-strategy")
    @Column(name = "ID")
    private String id;
    …


    @OneToMany(mappedBy = "group")
    private Set<GroupMember> members;



@Entity
@Table(name = "sb_msg_group_member")
public class GroupMember
{
    …

    @ManyToOne
    @JoinColumn(name = "USER_ID", nullable = false, updatable = true)
    private User user;

如何编写CriteriaBuilder(非JPQL)查询,我想查找具有一定数量成员的组?我尝试过以下方法:

    final CriteriaBuilder builder = m_entityManager.getCriteriaBuilder();
    CriteriaQuery<Group> criteria = builder.createQuery(Group.class);
    final List<Predicate> predicates = new ArrayList<Predicate>();
    final Root<Group> group = criteria.from(Group.class);
    predicates.add(builder.equal(builder.count(group.get(Group_.members)),users.size()));
    criteria.where(builder.and(predicates.toArray(new Predicate[predicates.size()])));
    final TypedQuery<Group> results = m_entityManager.createQuery(criteria);

但SQL导致语法异常,产生......

select group0_.ID as ID70_, group0_.CLASSROOM_ID as CLASSROOM3_70_, group0_.NAME as NAME70_, group0_.CREATOR as CREATOR70_ from group group0_ cross join group_member members1_ where group0_.ID=members1_.GROUP_ID and count(.)=2
  • 戴夫

1 个答案:

答案 0 :(得分:0)

predicates.add(builder.equal(builder.size(group.get(Group_.members)), users.size()));

可能就是你所需要的。