tags:

views:

56

answers:

2

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?

+3  A: 

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);
BalusC
+1  A: 

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.

Matthew Flynn
This implies a `static` session. You don't want to have that.
BalusC
True. I was treating the method as a function, which would mean adding the session as a parameter: public static <T> get(Session session, Class<T> cls, Long id);
Matthew Flynn
Actually you dont need the '<Entity>' in the method call.
Willi
You shouldn't need it, but some compilers will complain if you don't put it there.
Matthew Flynn