用于选择多个值的Hibernate查询

5n0oy7gb  于 2022-11-14  发布在  其他
关注(0)|答案(6)|浏览(164)

在Hibernate中,我可以执行以下操作

Query q = session.createQuery("from Employee as e");
List<Employee> emps = q.list();

现在,如果我想获取int和字符串,我该怎么做呢?

Query q = session.createQuery("SELECT E.firstName,E.ID FROM Employee E");
List ans = q.list();

现在,清单的结构将是什么?

owfi6suc

owfi6suc1#

这样挺好的。您需要了解的是,它将返回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];
         .....
     }
unguejic

unguejic2#

您将获得Object数组的列表(每个数组都有两个元素)

List< Object[] > employees = q.list();

for ( Object[] employee : employees ) {
    // employee[0] will contain the first name
    // employee[1] will contail the ID
}
bf1o4zei

bf1o4zei3#

您应该使用新对象来保存这些值,如下所示:

"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获得了这个示例

gwo2fgha

gwo2fgha4#

List<Object[]> is the structure.

因此,每个元素如下所示:

List ans = q.list();
for(Object[] array : ans) {
    String firstName = (String) array[0];
    Integer id = (Integer) array[1];
}
wfsdck30

wfsdck305#

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]);
}
q1qsirdb

q1qsirdb6#

不带迭代器:

@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();
}

相关问题