如何制作HQL查询对象而不是db?

时间:2013-10-18 03:30:58

标签: java sql hql

我是HQL的新手,这件事让我感到困惑。所以,这是我的功能:

public List<Map<String, Object>> getMyQuery(List<Country> country){
    String hql = "SELECT DISTINCT new map(a as accounts) ";
    hql += "FROM Account a WHERE a.location_id in "
                + "( "
                + "SELECT location_id FROM Location l WHERE l.address_id in "
                + "("
                + "SELECT id FROM Address adr WHERE adr.country_id in (:country)))";

    }
    Query query = getSession().createQuery(hql);
    if(country != null){
        query.setParameterList("country", country);
    }
    return query.list();
}

在我的日志文件中,我看到由于以下原因无法解析查询:

 Caused by: org.hibernate.QueryException: could not resolve property: country_id of: com.mypackage.myobjects.Address [SELECT id FROM com.mypackage.myobjects.Address adr WHERE adr.country_id in (:country)]

当我在使用SQL数据库上运行类似的查询时,一切都很好,但是这个查询中断了。我想知道为什么文件夹中的所有突然输出包?似乎正在对象而不是数据库上执行查询。我究竟做错了什么?

提前谢谢

1 个答案:

答案 0 :(得分:2)

正如错误日志所说,hibernate无法在类中找到名为“country_id”的属性 “com.mypackage.myobjects.Address”。可以是country_id是地址表中列的名称。

Hql适用于Pojo,尝试使用COUNrty_id列映射的Address类的映射属性。请参阅

If Address class is,
Class Address{

 @Column(name="country_id")
 private int countryId;

  ....
}

然后用“countryId”

替换hql查询中的“country_id”