我在使用hibernate的Query对象查询数据列表时,遇到如下报错:
ERROR [org.lujx.test.ManageCountry] - 查询信息失败 ,异常信息 :t_country is not mapped [from t_country]
我的数据表结构如下:
+------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+-------------+------+-----+---------+-----------------+
| c_id | int(11) | NO | PRI | NULL |auto_increment |
| c_name | varchar(20) | YES | | NULL | |
| c_location | varchar(50) | YES | | NULL | |
+------------+-------------+------+-----+---------+-----------------+
hibernate配置文件如下
<hibernate-mapping package="org.lujx.model"><class name=" Country" table=" t_country" catalog="lujx">
<id name="id" column="c_id">
<generator class="native"></generator>
</id>
<property name="name" column="c_name" length="20"></property>
<property name="location" column="c_location" length="50"></property>
</class>
</hibernate-mapping>
查询代码如下:
List<Country> countries = new ArrayList<Country>();
try {
Query query = session.createQuery("from t_country");
countries = query.list();
print(countries);
} catch (HibernateException e) {
LOGGER.error("查询信息失败 ,异常信息 :" + e.getMessage());
}finally {
session.close();
sessionFactory.close();
}
出现这个错误的根本原因是hql语法里面是POJO对象而不是table,所以应该将createQuery 参数修改为配置文件中所要查询的表名所映射的java实体类名,在此例中,正确的写法为:
Query query = session.createQuery("from Country");
ps:参数对大小写敏感,所以一定要注意大小写。
特此记录