Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate new keyword with distinct

I need to take hql that is currently :

select distinct a from Asset as a where ...

and change it to

select new com.org.AssetDTO(a.id, a.address, a.status) from Asset as a where ...

My problem is with the distinct keyword. Where does it belong in an hql query where you're using the new Object query type. One thought was to use a sub-select and have my distinct there. I've tried adding distinct a.id but that doesn't work.

like image 415
dstarh Avatar asked Aug 08 '11 15:08

dstarh


People also ask

How to use DISTINCT in Hibernate?

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 query?

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.

Can we use distinct in JPQL?

DISTINCT with JPQL entity queries. The DISTINCT keyword has a different purpose when it comes to entity queries. Without using DISTINCT , the JPA specification states that the returning entities resulting from a parent-child JOIN might contain object reference duplicates.

What is query uniqueResult () in Hibernate?

public Object uniqueResult() throws HibernateException. Convenience method to return a single instance that matches the query, or null if the query returns no results.


1 Answers

Ok for anyone interested the proper syntax is

select distinct new com.org.AssetDTO(a.id, a.address, a.status) from Asset as a where ...
like image 175
dstarh Avatar answered Nov 06 '22 23:11

dstarh