Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add Distinct in Hibernate Criteria

Tags:

java

hibernate

In my database I have a Test table, with columns: testName, testType there are 2 different tests with the same type I.e "SUN", so I want only one of them for which I use Distinct in my hibernate / criteria as below, but it still giving me both the types with the same name as "sun".

        Criteria crit = session.createCriteria(Test.class);      final ResultTransformer trans = new DistinctRootEntityResultTransformer();     crit.setResultTransformer(trans);     List rsList = trans.transformList(crit.list()); 

Any idea what could be the reason, or any other way of filtering duplicates.

like image 208
user1226162 Avatar asked May 24 '12 05:05

user1226162


People also ask

How to use Distinct in Hibernate Criteria?

You can add the DISTINCT keyword to your query to tell Hibernate to return each Author entity only once. But as you can see in the following log messages, Hibernate also adds the DISTINCT keyword to the SQL query. This is often not intended and might result in an efficient database query.

Can we use distinct in HQL?

Using distinct in the HQL Query We can notice that the distinct keyword was not only used by Hibernate but also included in the SQL query. We should avoid this because it's unnecessary and will cause performance issues.

What is Criteria query in Hibernate with example?

Hibernate provides alternate ways of manipulating objects and in turn data available in RDBMS tables. One of the methods is Criteria API, which allows you to build up a criteria query object programmatically where you can apply filtration rules and logical conditions.

What is the difference between criteria and criterion in Hibernate?

Criteria criteria= session.createCriteria(Order.class) It can be used as restrictions on the criteria query. In other words, Criterion is the object-oriented representation of the “where” clause of a SQL query. The conditions to be applied (also known as restrictions) can be provided by the Restrictions class.


1 Answers

Use Projections.distinct.

Criteria crit = session.createCriteria(Test.class).setProjection(     Projections.distinct(Projections.projectionList()     .add(Projections.property("type"), "type") ) .setResultTransformer(Transformers.aliasToBean(YourBean.class));   List lst = crit.list(); 

where YourBean.class has a property "type". The returned list will be List<YourBean>.

like image 60
Dandy Avatar answered Oct 23 '22 02:10

Dandy