Is there a way to create a Distinct query in HQL. Either by using the "distinct" keyword or some other method. I am not sure if distinct is a valid keywork for HQL, but I am looking for the HQL equivalent of the SQL keyword "distinct".
相关问题
- Django distinct is not working
- How does the JPA handle partial, non-disjoint inhe
- Tell hibernate hbm2ddl not create individual table
- Should there be an EntityManager per thread in Spr
- Hibernate and multiThread Logic
相关文章
- Hibernate Tutorial - Where to put Mapping File?
- Hibernate doesn't generate cascade
- Setup and Tear Down of Complex Database State With
- How to left join unrelated entities?
- How to map an abstract collection with jpa?
- Two foreign keys as primary key
- select “all columns” with “group by” in hibernate
- Hibernate JPA ManyToOne composite key
Here's a snippet of hql that we use. (Names have been changed to protect identities)
You can also use
Criteria.DISTINCT_ROOT_ENTITY
with Hibernate HQL query as well.Example:
Suppose you have a Customer Entity mapped to CUSTOMER_INFORMATION table and you want to get list of distinct firstName of customer. You can use below snippet to get the same.
I hope it helps. So here we are using group by instead of using distinct keyword.
Also previously I found it difficult to use distinct keyword when I want to apply it to multiple columns. For example I want of get list of distinct firstName, lastName then group by would simply work. I had difficulty in using distinct in this case.
You can you the distinct keyword in you criteria builder like this.
And create the field constructor in your model class.
I had some problems with result transformers combined with HQL queries. When I tried
it didn't work. I had to transform manually like this:
With Criteria API transformers worked just fine.
My main query looked like this in the model:
And I was still not getting what I considered "distinct" results. They were just distinct based on a primary key combination on the table.
So in the
DaoImpl
I added an one line change and ended up getting the "distinct" return I wanted. An example would be instead of seeing 00 four times I now just see it once. Here is the code I added to theDaoImpl
:I hope this helped! Once again, this might only work if you are following coding practices that implement the service, dao, and model type of project.