HibernateTemplate query with combo box

Beginning hibernation here, this is probably the main question.

Let's say I have two hibernate objects: Employee

and Department

in a one-to-many relationship. One department can have many Employees

.

I have List

objects Department

and you want to get all Employees

that are in these departments. For example, in SQL it's easy:

Select * from Employee where Employee.deptID in (1, 2, 6, 19);

      

What is the correct and correct way to do this in a search HibernateTemplate

? The example I saw seems hopelessly detailed and involves creating a list departmentIDs

and then overriding executeFind()

. Can I do this directly using List<Department>

instead of creating a list of object IDs?

//Verbose example
List Employees = getHibernateTemplate().executeFind(new HibernateCallback<List>() {
    @Override
    public List doInHibernate(Session session) throws HibernateException, SQLException {
        Query query = session.createQuery(
                "select employee" +
                        "from employee e " +
                        "where e.deptID in (:ids) "
        );
        query.setParameterList("ids", ids);
        return query.list();
    }
});

      

+3


source to share


2 answers


Assuming you have a department property in Employee, you can run this query:



List<Departement> departments = ...

List Employees = getHibernateTemplate().executeFind(new HibernateCallback<List>() {
    @Override
    public List doInHibernate(Session session) throws HibernateException, SQLException {
        Query query = session.createQuery(
                "select employee" +
                        "from employee e " +
                        "where e.department in (:departments) "
        );
        query.setParameterList("departments", departments);
        return query.list();
    }
});

      

+1


source


I assume you have two employees Employee and Department, In Department you have a list of employees and you want to get that list based on department IDs.

SELECT emp FROM department d join d.employees emp where d.deptID in(:ids);

      



This is the best way to do it. He will provide you with a list of employees.

I do not give you spring way of requesting but this might help you

-1


source







All Articles