Reputation: 155
I am building generic methods for queries to the database with Hibernate, the following method consults the information of an entity by primary key.
@PersistenceContext(unitName = "UnitPers")
private EntityManager entity;
public Object findByPk(Class clazz, Object pk) throws Exception {
Object obj = null;
try {
obj = entity().find(clazz, pk);
} catch (Exception e) {
throw e;
}
return obj;
}
This method works correctly, but I do not want to make a cast (object to myTypeEntity) when making the call.
private myTypeEntity entity;
entity = (myTypeEntity) findByPk(myTypeEntity.class, new Bigdecimal("1"));
//GET and SET Methods
I want to avoid doing the cast when calling this method, bearing in mind that it is one of the purposes of the generic, but I have not managed to do it, any ideas? or what I intend to do is not possible.
Upvotes: 0
Views: 126
Reputation: 19926
By introducing a generic type variable on the method level you can define what type should be returned, this can be seen in @cpr4t3s' answer.
You can also shorten his snippet to the following:
public <T> T findByPk(Class<T> clazz, Object pk) throws Exception {
return entity().find(clazz, pk);
}
Because:
catch
-blockobj
-variableUpvotes: 1
Reputation: 1445
You can use generics instead of using Object:
public <T> T findByPk(Class<T> clazz, Object pk) throws Exception {
T obj = null;
try {
obj = entity().find(clazz, pk);
} catch (Exception e) {
throw e;
}
return obj;
}
And then it should work without doing the cast
private myTypeEntity entity;
entity = findByPk(myTypeEntity.class, new Bigdecimal("1"));
Upvotes: 2