How to get the primary key of any JPA object?

For each @Entity, I need to do the following:

public <Entity> boolean insert(final Entity entity){ if (em.find(entity.getClass(), entity.getId()) == null) { et.begin(); em.persist(entity); et.commit(); return true; } return false; } 

This is preserved in essence if it does not exist, and to know whether it was or not. With Entity, I try to achieve @Entity, although I understand that this is not an inheritance relationship. What class can I use to reference every JPA object? I could just create an interface / abstract class MyEntities and inherit all of them, but is that so? I hope for less code. Also, I expect that I can extract the primary key for each object as I try in .getId ().

+13
java eclipselink
Jul 25 '10 at 10:21
source share
4 answers

This functionality was added in JPA 2.0. Just call:

 Object id = entityManagerFactory.getPersistenceUnitUtil().getIdentifier(entity); 
+36
Jul 26 '10 at 13:10
source share

The general front-end approach is what I use and it works great. Using pure JPA, I see no way to get the identifier.

Take a look at merge() . I did not use it myself, but I think

Hibernate has ways to do it

 Serializable id = session.getIdentifier(entity); 

But this is not a JPA standard.

+4
Jul 25 '10 at 11:02
source share

Read the article on Dao 's General Approach .

I do not understand your problem, but if you want to get the identifier of an object, just get it. Its available method after saving is completed, i.e.

 em.persist(entity); et.commit(); int id = entity.getId() 

I usually make an AbstractEntity class with the id field and its accessories and inherit all my other objects from this class.

The only problem with this approach is that if you need to make any of your entities Serializable, you will have to make AbstractEntity serializable, i.e. all other objects will become serializable. Otherwise, the id field will not be serialized in the entity to be serialized.

+4
Jul 25 '10 at 11:13
source share

Another way to get the object id:

 Session session = entityManager.unwrap(Session.class); Object entityId = session.getId(entity); 

This approach uses the extractPrimaryKeyFromObject () method from the ObjectBuilder class.

0
06 Sep '17 at 11:22 on
source share



All Articles