deamon
deamon

Reputation: 92519

Convert a list of IDs into a list of objects with an ORM like Hibernate

In web applications it is common to send a list of IDs to the server when selecting elements of a collection. There could be a HTML form representing a course and it would contain a list with all students of a semester. By selecting some students they would be associated with the course. The server would receive a list of student IDs.

What is the best practise to convert this list of IDs (primary keys in the DB) into a list of domain objects with an ORM like Hibernate? I'd like to avoid to write the same code for each domain class again. Grails does something like that (but I don't know how).

Upvotes: 3

Views: 1741

Answers (1)

lweller
lweller

Reputation: 11327

so we have a generic DAO with a method like this

public <T extends IDomainObject> List<T> getAll(Class<T> type, List<Integer> ids) {
    return (List<T>) session.createCriteria(type).add(Restrictions.in("id", ids).list();
}

By convention all our domain model objects implements IDomainObject and have a primary key field named id.

Upvotes: 4

Related Questions