Hibernate query for selecting multiple values

前端 未结 6 1770
鱼传尺愫
鱼传尺愫 2020-12-13 19:32

In hibernate I can do following

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

Now if I want to

相关标签:
6条回答
  • 2020-12-13 20:12

    You should use a new object to hold these values, just like this:

    "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()
    

    I've got this example from http://www.java2s.com/Tutorial/Java/0355__JPA/EJBQLCreatenewObjectInSelectStatement.htm

    0 讨论(0)
  • 2020-12-13 20:20

    Without iterators:

    @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();
    }
    
    0 讨论(0)
  • 2020-12-13 20:26
    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]);
    }
    
    0 讨论(0)
  • 2020-12-13 20:35

    This is fine. Only thing you need to understand is that it will return list of Object [] as below:

         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];
             .....
         }
    
    0 讨论(0)
  • 2020-12-13 20:36
    List<Object[]> is the structure.
    

    So you get each element like this:

    List ans = q.list();
    for(Object[] array : ans) {
        String firstName = (String) array[0];
        Integer id = (Integer) array[1];
    }
    
    0 讨论(0)
  • 2020-12-13 20:38

    You will get a list of arrays of Objects (each one with two elements)

    List< Object[] > employees = q.list();
    
    for ( Object[] employee : employees ) {
        // employee[0] will contain the first name
        // employee[1] will contail the ID
    }
    
    0 讨论(0)
提交回复
热议问题