I would like to return a list that has unique elements based on a property type. For instance this property can be a Customer-name which can occur many times but I only need just the one object with just one occurrence of a customer-name, hence the list should contain a list of objects but the property of customer names would be unique. Is this possible using criterions/criteria API?
Asked
Active
Viewed 98 times
2
-
So what is the selection criteria? Is it unique in your database? – Amir Pashazadeh Mar 09 '12 at 10:16
-
No. I just want to return a list of objects but for each object return one of the objects' property value would be unique – Dark Star1 Mar 09 '12 at 10:48
-
So, if there are duplicates arbitrarily pick something and return? – ManuPK Mar 09 '12 at 11:09
-
Not sure I understand what you're asking but I will return a list of objects with a property value that's unique within the list of the returned objects. So object1.customer_name is unique within the returned list, even though that customer name may be occur more than once in the table. – Dark Star1 Mar 09 '12 at 11:52
-
What you are asking is usually not very useful to the application. "arbitrary pick something and return it" means you are in effect asking for a random selection of object to be returned that has a unique 'name'. It is more useful to want a list (or rather a 'set') of names out of the query. Part of the limitation is that the SQL DISTINCT keyword usually applies to the entire row of data returned, maybe some SQL implementation allow 'DISTINCT(c.columnName), c.*' but that is not an SQL standard grammar. See tricks in http://stackoverflow.com/questions/966176/select-distinct-on-one-column – Darryl Miles Sep 13 '12 at 12:57
-
@DarrylMiles I am not asking to "arbitrarily pick something and return it" I want(ed) to "return a list from the db wherein there's a uniqueness in compound properties" e.g "return list of all purchased_item wherein customer name is unique within the list" so the resulting list will contain purchased_item subsets but with customer being unique within that subset. – Dark Star1 Oct 14 '12 at 23:07
1 Answers
1
Use Projections along with Criteria
criteria.setProjection(Projections.distinct(Projections.property("name")));
Or
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

Hardik Mishra
- 14,779
- 9
- 61
- 96
-
1This will return the list of **unique names**, where OP is asking the Objects with the distinct name. – ManuPK Mar 09 '12 at 10:53