我有一个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);
}
因此,我想通过列名获取id
和name
的值,有什么办法吗?
答案 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();
}`