如何使用Hibernate Criteria选择嵌套属性 [英] How to select nested property using Hibernate Criteria

查看:427
本文介绍了如何使用Hibernate Criteria选择嵌套属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个实体,例如注册,用户和国家。基本上,注册属于用户,用户属于一个国家。现在我正试着从注册中选择国家名称,如下所示:

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

失败并给我:

错误:org.hibernate.engine.jdbc.spi.SqlExceptionHelper  - '字段列表'中的未知列'usercountr1_.name'
org.hibernate.exception.SQLGrammarException:未知列'

生成的Hibernate查询:

  Hibernate:从voucherList中选择usercountr1_.name作为y0_ this_ 

我注意到在sql中没有加入。这就是查询失败的原因吗?如何解决这个问题?

解决方案

尝试类似于



<$ p $标准条件= getSession()。createCriteria(Registration.class);
ProjectionList projectionList = Projections.projectionList();

criteria.createAlias(user,u); //这里我改变了
criteria.createAlias(u.country,usercountry); //这里我改变了

projectionList.add(Projections.property(usercountry.name),usercountry.name);
criteria.setProjection(projectionList);
criteria.list();


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 ?

解决方案

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

这篇关于如何使用Hibernate Criteria选择嵌套属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆