Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select nested property using Hibernate Criteria

Tags:

hibernate

I have three entities such as Registration, User and Country. Basically a registration belongs to a user and a user belongs to a country. Now I am trying to select country name from registration with the following

        Criteria criteria = getSession().createCriteria(Registration.class);
        ProjectionList projectionList = Projections.projectionList();
        criteria.createAlias("user.country", "usercountry");
        projectionList.add(Projections.property("usercountry.name"),"usercountry.name");
        criteria.setProjection(projectionList);
        criteria.list();

This fails and give me :

ERROR: org.hibernate.engine.jdbc.spi.SqlExceptionHelper - Unknown column 'usercountr1_.name' in 'field list'
org.hibernate.exception.SQLGrammarException: Unknown column 'usercountr1_.name' in 'field list'

Generated Hibernate query :

Hibernate: select usercountr1_.name as y0_ from voucherList this_

I noticed there's no join in the sql. Is this why the query failed ? How can I fix this ?

like image 746
abiieez Avatar asked Nov 06 '13 09:11

abiieez


1 Answers

try something like

Criteria criteria = getSession().createCriteria(Registration.class);
ProjectionList projectionList = Projections.projectionList();

criteria.createAlias("user", "u");  // here i changed 
criteria.createAlias("u.country", "usercountry");  //  here i have changed 

projectionList.add(Projections.property("usercountry.name"),"usercountry.name");
criteria.setProjection(projectionList);
criteria.list();
like image 192
Nikson Kanti Paul Avatar answered Sep 29 '22 11:09

Nikson Kanti Paul