一尘不染

如何使用休眠条件选择嵌套属性

hibernate

我有三个实体,例如注册,用户和国家。基本上,注册属于用户,而用户属于国家。现在,我正在尝试通过以下方式从注册中选择国家/地区名称

        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();

这失败了,给我:

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'

生成的hibernate查询:

Hibernate: select usercountr1_.name as y0_ from voucherList this_

我注意到在sql中没有联接。这就是为什么查询失败?我怎样才能解决这个问题 ?


阅读 267

收藏
2020-06-20

共1个答案

一尘不染

尝试像

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();
2020-06-20