0

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.

1
  • If you want to use an existing framework for that , have a look at spring data Commented Jun 13, 2018 at 23:41

2 Answers 2

2

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")); 
Sign up to request clarification or add additional context in comments.

Comments

1

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:

  1. You're just throwing the exception up in the catch-block
  2. You're doing nothing, but return the obj-variable

1 Comment

Thanks for your input, I'm still a novice. I'll put into practice. regards

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.