我有一个 SQL
查询,其中我使用了7个以上的表。
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
的值,有什么方法吗?
您可以使用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();
}`