在休眠状态下,我可以执行以下操作
Query q = session.createQuery("from Employee as e);
List<Employee> emps = q.list();
现在,如果我想获取 int 和 String 我该怎么做?
Query q = session.createQuery(""SELECT E.firstName,E.ID FROM Employee E";
List ans = q.list();
现在列表的结构是什么?
这可以。您唯一需要了解的是,它将返回Object []
如下列表:
Query q = session.createQuery("select e.id, e.firstName from Employee e");
List<Object[]> employees= (List<Object[]>)q.list();
for(Object[] employee: employees){
Integer id = (Integer)employee[0];
String firstName = (String)employee[1];
.....
}
您将获得Object
s 数组的列表(每个数组有两个元素)
List< Object[] > employees = q.list();
for ( Object[] employee : employees ) {
// employee[0] will contain the first name
// employee[1] will contail the ID
}
Query qry=session.createQuery("select e.employeeId,e.employeeName from Employee e where e.deptNumber=:p1");
qry.setParameter("p1",30);
List l2=qry.list();
Iterator itr=l2.iterator();
while(itr.hasNext()){
Object a[]=(Object[])itr.next();
System.out.println(a[0]+"/t"a[1]);
}
您应该使用一个新对象来保存这些值,就像这样:
"SELECT NEW EmpMenu(e.name, e.department.name) "
+ "FROM Project p JOIN p.students e " + "WHERE p.name = :project "
+ "ORDER BY e.name").setParameter("project", projectName).getResultList()
我从http://www.java2s.com/Tutorial/Java/0355__JPA/EJBQLCreatenewObjectInSelectStatement.htm得到了这个例子
List<Object[]> is the structure.
所以你得到这样的每个元素:
List ans = q.list();
for(Object[] array : ans) {
String firstName = (String) array[0];
Integer id = (Integer) array[1];
}
没有迭代器:
@SuppressWarnings( "unchecked" )
public List<Employee> findByDepartment(long departmentId){
SQLQuery query = session.createSQLQuery("SELECT {emp.*} " +
" FROM employee emp " +
+"WHERE emp.department_id = :departement_id");
query.setLong("department_id", departmentId);
query.addEntity("emp", Employee.class);
return (List<Employee>) = query.list();
}