How to use setProjection correctly?
I only want to get certain columns in my UserAccount class, so I have below code:
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 zero in return. But if I comment out setProjections, I get the user with all properties. How can I use setProjection correctly in this case?
0
source to share
2 answers
It returns an array of objects, 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();
0
source to share
With projections, we have to use result transformation and anti-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:
0
source to share