mrblah
mrblah

Reputation: 103487

using load/get using generics

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?

Upvotes: 1

Views: 1309

Answers (2)

Matthew Flynn
Matthew Flynn

Reputation: 2238

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.

Upvotes: 1

BalusC
BalusC

Reputation: 1108632

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);

Upvotes: 5

Related Questions