Hibernate原生查询返回的数据读取问题

1、Hibernate用原生SQL查询数据,这里query.list() 返回的是一个 对象数组;而我却将一个对象数组转为 实体类对象list,这里报出 java.lang.ClassCastException (cannot be cast to com.entity.Employee),这里就像有两个类(A类与B类) A a = new A();  B  b  = (B)a;这样就会出这个异常。     

String sql = "SELECT " +
"e.employee_id, " +
"e.last_name, " +
"e.emall, " +
"e.salary " +
"FROM " +
"departments as d left join employess AS e " +
"ON d.department_id = e.department_id " +
"WHERE d.department_id = '2'";


SessionFactory sf = hibernateTemplate.getSessionFactory();
Session session=sf.openSession();
Query query = session.createSQLQuery(sql);
List<Employee> list = query.list();
for(Employee employee : list) {
  System.out.println(employee.getLast_name());
}

  解决办法:在  session.createSQLQuery(sql)后面加上 .addEntity(Employee.class) ,Employee 是实体类

String sql = "SELECT " +
"e.employee_id, " +
"e.last_name, " +
"e.emall, " +
"e.salary " +
"FROM " +
"departments as d left join employess AS e " +
"ON d.department_id = e.department_id " +
"WHERE d.department_id = '2'";


SessionFactory sf = hibernateTemplate.getSessionFactory();
Session session=sf.openSession();
Query query = session.createSQLQuery(sql).addEntity(Employee.class);
List<Employee> list = query.list();
for(Employee employee : list) {
  System.out.println(employee.getLast_name());
}

 

2、上面写完启动项目测试时,遇到 java.sql.SQLException: Column 'department_id' not found. 这个错误,没有找到 department_id,意思就是在查询出来的结果集中没有 department_id这属性,在SQL中加上 e.department_id 就解决了这个问题。

String sql = "SELECT " + 
                    "e.employee_id, " + 
                    "e.department_id, " + 
                    "e.last_name, " + 
                    "e.emall, " + 
                    "e.salary " + 
                    "FROM " + 
                    "departments as d left join employess AS e " + 
                    "ON d.department_id = e.department_id " + 
                    "WHERE d.department_id = '2'";

 

解决完这个问题就能正常输出数据了,此篇幅为了学习,望大神多多指教

posted on 2018-04-17 20:54  狮子与我  阅读(212)  评论(0编辑  收藏  举报

导航