简体   繁体   中英

Hibernate Criteria to find Duplicates

I want to get the duplicate entries. I want to use the query as criteria, for this i am using the below code.

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

The Hibernate mapping is like

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

How can I get list of A that have duplication in 'field' column?

You can pretty much translate your query one to one to HQL (warning: untested).

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
)

My own answer according prompted 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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM