zoukankan      html  css  js  c++  java
  • 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'";

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

  • 相关阅读:
    NYOJ题目916胖子小的百宝袋
    NYOJ题目893十字架
    NYOJ题目874签到
    设计模式之Singleton
    Elo rating system 模拟
    JDBC之SqlHelper
    《Thinking in Java》十四章类型信息_习题解
    NYOJ题目842整除的尾数
    NYOJ题目840吃花生
    NYOJ题目839合并
  • 原文地址:https://www.cnblogs.com/LionsEyes/p/8869949.html
Copyright © 2011-2022 走看看