7
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); 
Susie
  • 5,038
  • 10
  • 53
  • 74
  • 3
    Have you tried using a `LinkedHashSet`? That will preserve the order, i think. – yamafontes Oct 25 '13 at 20:42
  • 2
    Maybe that should help: [can-hibernate-return-a-collection-of-result-objects-other-than-a-list](http://stackoverflow.com/questions/416970/can-hibernate-return-a-collection-of-result-objects-other-than-a-list) – baltov Oct 25 '13 at 20:44
  • Are you looking for this? http://stackoverflow.com/questions/10731723/how-to-add-distinct-in-hibernate-criteria – Taylor Oct 26 '13 at 00:58

2 Answers2

8

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.

limc
  • 39,366
  • 20
  • 100
  • 145
  • 1
    Do we get the list of employee object or just employee Id? I tried using this code and it would just return the list of id instead of list of object. – MR AND Dec 17 '18 at 15:31
3

As the comments and javadoc suggest, you have to return a List from Criteria. Therefore, your only option is to remove uniques after the fact. As KepaniHaole said, you should use a LinkedHashSet if you want to preserve order.

Daniel Kaplan
  • 62,768
  • 50
  • 234
  • 356