Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return a set instead of list with hibernate Criteria

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, in order to remove duplicate data?

I understand I can achieve this by creating a set out of the returned list like below, but then I would lose the sorting order of the list. And I don't want to have to write code to sort the set.

Set<Employee> empSet = new HashSet<Employee>(result); 
like image 269
Susie Avatar asked Oct 25 '13 20:10

Susie


1 Answers

I don't think it's possible to return a Set using Criteria based on the javadoc. However, if you want to remove duplicate data, why don't add a Projections.distinct(...) to your existing Criteria to remove the duplicates?

http://docs.jboss.org/hibernate/envers/3.6/javadocs/org/hibernate/criterion/Projections.html

UPDATE

For example, if you want to apply a SELECT DISTINCT on the employee name (or some identifier(s)) 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();

This way, you don't really need to worry about using Set at all.

like image 115
limc Avatar answered Sep 23 '22 03:09

limc