我出现的错误是:oorg.hibernate.hql.ast.QuerySyntaxException: DEPT is not mapped [from DEPT]
配置文件如下:
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="cn.lex.entity"> <class name="Dept" table="DEPT"> <id name="deptno" column="deptno"> <generator class="native"/> </id> <property name="dname"></property> <property name="loc"></property> </class> </hibernate-mapping >
代码如下:
package cn.lex.test; import cn.lex.entity.Dept; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.util.List; /** * Created by accp on 2017/1/9. */ public class SecondTest { Session session; Transaction tx; @Before public void before(){ Configuration cfg=new Configuration().configure(); SessionFactory factory=cfg.buildSessionFactory(); session=factory.openSession(); tx=session.beginTransaction(); } @Test public void page(){ String hql="from DEPT order by DEPTNO"; //创建query对象 Query query = session.createQuery(hql); //每页显示几条数据 int pageSize=2; //设置第一页 int pageIndex=1; //设置每页显示的最大记录数 query.setMaxResults(pageSize); //设置从第几条开始输出 query.setFetchSize((pageIndex-1)*pageSize); List<Dept> list = query.list(); for (Dept dept:list) { System.out.println("部门编号:"+dept.getDeptno()); } } @After public void after(){ tx.commit(); session.close(); } }
而出现这个错误的根本原因是hql语法里面是POJO(Plain Ordinary Java Object)对象而不是table.所以改成这样就可以了:
List<Dept> list=session.createQuery("from Dept order by DEPTNO”).list();
特记于此!以备勿忘!