Hibernate Criteria查找重复项

时间:2013-12-18 12:11:46

标签: java count group-by hibernate-criteria

我想获得重复的条目。我想使用查询作为标准,为此我使用下面的代码。

SELECT * from A 
WHERE field in (
     SELECT field from A 
     GROUP BY field HAVING COUNT(field) > 1
);

Hibernate映射就像

@Entity
class A{
    ...
    private String field;
    ...
}

如何在“字段”列中获取有重复的A列表?

2 个答案:

答案 0 :(得分:3)

您几乎可以将查询一对一翻译为HQL(警告:未经测试)。

select A
from A a 
where a.field in (
   select ai.field 
   from A ai
   group by ai.field -- assumes that by f you mean field 
   having count(a1.field) > 1
)

答案 1 :(得分:1)

根据提示Anthony Accioly

我自己的答案
final Criteria searchCriteria = session.createCriteria(A.class);

...

final DetachedCriteria d1 = DetachedCriteria.forClass(A.class);
d1.setProjection(Projections.count("field"));
d1.add(Restrictions.eqProperty("field", "AA.field"));

final DetachedCriteria d2 = DetachedCriteria.forClass(A.class, "AA");
d2.setProjection(Projections.projectionList()
.add(Projections.groupProperty("field")));
d2.add(Subqueries.lt(1L, d1));

criteria.add(Property.forName("field").in(d2));