Question

I'm trying to perform a query with the 'distinct' HQL clause in hibernate and get a List. But, whenever I use 'ditinct' I get a List of java objects instead of the POJOs which are returned without using 'distinct'. Is there a good way to get the pojos instead of objects?

EXAMPLE that returns a list of POJOs as expected:

class myPojos () { ... (has some properties/fields) propOne, propTwo, propThree ...}

Inside a DAO

Session s = HibernateUtil.currentSession();

List<myPojos> myPojoList = s
                .createQuery( "select from " getPojoClass().getName())
                .list();

However, adding a 'distinct' clause

List<myPojos> myPojoList = s
                .createQuery( "select distcinct mpl.propOne, mpl.propTwo, mpl.propThree from " + getPojoClass().getName() + "mpl" )
                .list();

...instead returns a List of objects. So, I loose all the getters and setters of myPojos class and loose type-safetey.

Is there a way to do this and get a List to retatin getters/setteres & type-saftey?

Was it helpful?

Solution

You could use the following approach: select p from Pojo p where p.id in (select distinct id from Pojo). You are performing the distinct in a subquery, letting to the main query just the selection of the ids already unique selected.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top