0

With HQL I can enter the following statement can be made :

SELECT new MyClass(u.name,u.email) FROM User u ;

where MyClass is a normal Javabean with name and email as a Constructor.

I like to use Hibernate Criteria to construct such queries. Is this possible. I know I can restrict the columns to name and email using Projections but how do I get to use the new operator in Criteria ?

2 Answers2

2

You should use

.setResultTransformer(Transformers.aliasToBean(MyClass.class));

This is very good example Hibernate Criteria Transformers.aliasToBean

Community
  • 1
  • 1
mvb13
  • 1,514
  • 3
  • 18
  • 33
1

Every time I look at Criteria API code I remember why I avoid using it: Anyway see 9.1.4 here:

http://docs.jboss.org/hibernate/entitymanager/3.5/reference/en/html/querycriteria.html#querycriteria-typedquery-multiselect

Alan Hay
  • 22,665
  • 4
  • 56
  • 110
  • Yes this solution works. Thanks. Kind of like the criteria builder but I suppose its just personal taste. – Marcus Blackhall Oct 29 '13 at 12:05
  • Previously accepted answer looks a bit easier to work with however as you do not need a large constructor. For stongly typed queries I have been using QueryDsl recently which I find much simpler. – Alan Hay Oct 29 '13 at 12:15