With Hibernate, how do I load an entity using generics?
Curretly I am doing:
Entity e = (Entity) session.load(Entity.class, 123);
In NHibernate, with generics, I can do:
session.Get<Entity>(123);
What's the Hibernate equivalent?
With Hibernate, how do I load an entity using generics?
Curretly I am doing:
Entity e = (Entity) session.load(Entity.class, 123);
In NHibernate, with generics, I can do:
session.Get<Entity>(123);
What's the Hibernate equivalent?
Unfortunately, Java doesn't support Reified Generics yet.
Best what you could do is to wrap it in another convenience method to remove the need to cast:
public <T> T get(Class<T> cls, Long id) {
return cls.cast(session.load(cls, id));
}
which can be used as follows:
Entity e = get(Entity.class, 123);
To add to BalusC's answer, you can be more explicit in the call to the generic wrapper method. So, if the wrapper method is in a a class GenericSession:
public class GenericSession {
private GenericSession() {}
public static <T> T get(Class<T> cls, Long id) {
return cls.cast(session.load(cls, id));
}
}
You can call it like so:
Entity e = GenericSession.<Entity>get(Entity.class, 123);
This should give you a better idea of how things are cast.