views:

40

answers:

2

How do I load a collection of entities of a given class, with only a single trip to the database, e.g.:

 public Collection<Object> getEntities(Class<?> entityClass,Collection<Serializable> listOfIDs);

I know that if I were only wanting to fetch a single entity, I could use:

sessionFactory.getCurrentSession().get(Class,Serializable);

but there doesn't seem to be a matching option for a collection of Serializables.

Note that as I only know the class, I don't know the name of the Identity Column, so simple HQL / Criteria API is not an option, without first discovering the ID column.

+2  A: 

Can't you just execute an HQL query - "from MyEntity where ...", which will return a list of the entities? Just build the where clause manually. Another option is to use Criteria API.

Edit: Use "where id = ...". Hibernate will automatically find the id column for you, no matter how it is named.

Petar Minchev
You can't use either of these options (that I can see) without knowing the name of the identity column.
Marty Pitt
Ah OK, I get what you want to do now:)
Petar Minchev
..however, that was unclear, so I've clarified the question
Marty Pitt
You can use "id" in the where clause and Hibernate will automatically find the identity column.
Petar Minchev
A: 

Hibernate does not provide support for that out of the box. But you can achieve this in HQL with the help of the special id property:

14.5. Referring to identifier property

There are 2 ways to refer to an entity's identifier property:

  • The special property (lowercase) id may be used to reference the identifier property of an entity provided that the entity does not define a non-identifier property named id.
  • If the entity defines a named identifier property, you can use that property name.

So you could do something like this:

Query q = session.createQuery("from " + clazz.getName() + " where id IN :idList")
Pascal Thivent