Return a set instead of a list with a sleeping criterion

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 can I make it return a Set of Employee objects instead to remove duplicate data?

I understand that I can achieve this by creating a collection from the returned list, as shown below, but then I lose the sort order of the list. And I do not want to write code to sort the set.

 Set<Employee> empSet = new HashSet<Employee>(result); 
+6
source share
2 answers

I don’t think you can return Set using javadoc-based Criteria . However, if you want to remove duplicate data, why not add Projections.distinct(...) to your existing Criteria 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 something like this: -

 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(); 

Thus, you do not need to worry about using Set at all.

+7
source

As comments and javadoc point out, you should return List from Criteria . Therefore, your only option is to remove uniques after this fact. As Kepani Haole said, you should use the LinkedHashSet if you want to keep order.

+2
source

Source: https://habr.com/ru/post/956750/


All Articles