如何通过Java中的列名从query.list()获取值

时间:2019-02-24 16:43:30

标签: spring hibernate

我有一个SQL查询,在其中我使用了超过7个表的join。

 SQLQuery q = session.createSQLQuery("select e.id,e.name,e.email from emp as  e 
 inner join some 2/3 tables");
 List<Object[]> listObject = q.list();
 List<Employee> emp = new ArrayList<>();
 for(Object[] result : listObject){
 Employee e = new Emplyee();
 e.setId(result[0].toString());
 e.setName(result[1].toString());
 emp.add(e);
 }

因此,我想通过列名获取idname的值,有什么办法吗?

1 个答案:

答案 0 :(得分:0)

您可以使用query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);。     `

try {
         tx = session.beginTransaction();
         String sql = "SELECT firstName, salary FROM EMPLOYEE";
         SQLQuery query = session.createSQLQuery(sql);
         query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
         List empList= query.list();
         for(Object object : empList) {
            Map row = (Map)object;
            System.out.print("FirstName: " + row.get("firstName")); 
            System.out.println("Salary: " + row.get("salary")); 
         }
         tx.commit();
      } catch (HibernateException e) {
         if (tx!=null) tx.rollback();
         e.printStackTrace(); 
      } finally {
         session.close(); 
      }`