Java – use hibernate criteria to return set instead of list
criteria = createCriteria("employee");
criteria = createCriteria("employee"); criteria.add(Restrictions.eq("name","John")); criteria.addOrder(Order.asc("city")); criteria.addOrder(Order.asc("state")); List result = criteria.list();
This statement returns a list of employee objects How to make it return a set of employee objects to remove duplicate data?
I know I can do this by creating a return list setting, as shown below, but then I will lose the sort order of the list And I don't want to write code to sort collections
Set<Employee> empSet = new HashSet<Employee>(result);
Solution
I don't think we can use Javadoc based criteria to return set However, if you want to remove duplicate data, why not add projects. To the existing conditions Distinct (...) to remove duplicates?
http://docs.jboss.org/hibernate/envers/3.6/javadocs/org/hibernate/criterion/Projections.html
UPDATE
For example, if you want to apply select distinct to an employee name (or some identifier) to get a list of unique employees, you can do the following: –
List result = session.createCriteria("employee") .setProjection(Projections.distinct(Projections.property("name"))) .add(Restrictions.eq("name","John")) .addOrder(Order.asc("city")) .addOrder(Order.asc("state")) .list();
This way, you don't have to worry about using set