Java – hibernate conditions use group by and return entity list
I'm trying to use group by in my standard I need to do this:
SELECT b FROM Book b GROUP BY volumeCode;
I have the following code:
Criteria c = s.createCriteria(Book.class); c.setProjection(Projections.projectionList().add(Projections.groupProperty("volumeCode"))); List<Book> result = c.list();
However, this standard only returns volumecodes (string list) I need a list of books So I try to use Transformers:
Criteria c = s.createCriteria(Book.class); c.setProjection(Projections.projectionList().add(Projections.groupProperty("volumeCode"))); c.setResultTransformer(Transformers.aliasToBean(Book.class)); List<Book> result = c.list();
This code returns a list of null values Is it possible to use standards to do this?
Solution
First, projecton filters the amount of data retrieved. If you want more data, you should also add these attributes to the projection
Example:
c.setProjection( Projections.projectionList() .add( Projections.property("id").as("id") ) .add( Projections.property("descripction").as("description") ) .add( Projections.groupProperty("volumeCode").as("volumeCode") ));
Now, the converter executes what it calls "alias to bean", which matches the alias with the properties of the Java Bean "book. Java"
Edit:
Without a transformer, if the projection has multiple attributes, the results are as follows:
for(Object[] item:criteria.list()){ System.out.println( (String)item[0] ); //ID System.out.println( (String)item[1] ); //Description System.out.println( (String)item[2] ); //Volume code }
That's why you get cast exceptions about the transformer and try to match each alias to the property name of your java bean