0

I want to retrieve only certain columns in my UserAccount class so I have the code below:

UserAccount aUser = (UserAccount)currentSession().createCriteria(UserAccount.class) /* .setProjection(Projections.projectionList() .add(Projections.property("id")) .add(Projections.property("username")) .add(Projections.property("email")) .add(Projections.property("displayname"))) */ .add(Restrictions.eq("email", email)) .add(Restrictions.eq("password", password)) .add(Restrictions.eq("enabled", true)) .add(Restrictions.eq("role", Role.CUSTOMER)) .uniqueResult(); System.out.println(aUser); return aUser; 

I got the null in return. But If I comment out the setProjections, I will get the user with all the properties. How can I use setProjection correctly in this case?

2 Answers 2

0

It returns an Object array, so the code should be:

Object[] rows = (Object[]) session .createCriteria(UserAccount.class) .setProjection( Projections.projectionList() .add(Projections.property("id")) .add(Projections.property("username")) .add(Projections.property("email")) .add(Projections.property("displayname"))) .add(Restrictions.eq("email", email)) .add(Restrictions.eq("password", password)) .add(Restrictions.eq("enabled", true)) .add(Restrictions.eq("role", Role.CUSTOMER)) .uniqueResult(); 
Sign up to request clarification or add additional context in comments.

Comments

0

With projections we should use result transformer and aliasing:

UserAccount aUser = (UserAccount)currentSession() // FROM .createCriteria(UserAccount.class) // WHERE .add(Restrictions.eq("email", email)) .add(Restrictions.eq("password", password)) .add(Restrictions.eq("enabled", true)) .add(Restrictions.eq("role", Role.CUSTOMER)) // SELECT with alias .setProjection(Projections.projectionList() .add(Projections.property("id"),"id") // alias is a must for .add(Projections.property("username"),"username") // result transformer .add(Projections.property("email"),"email") .add(Projections.property("displayname"),"displayname") ) // here we go - this will convert projection into entity .setResultTransformer(Transformers.aliasToBean(UserAccount.class)) .uniqueResult(); 

Check:

1 Comment

Wow, I see, you prefer object[], weird... enjoy Hibernate anyhow ;)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.