Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the primary key of any JPA entity?

For every @Entity I need to perform 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;
}

That is persist the entity if it didn't exist, and know if it did or not exist. With Entity I'm trying to reach @Entity, although I realize it's not an inheritance relationship. What class can I use to refer to every JPA entity? I could just create an interface/abstract class MyEntities and have all of them inherit, but is that the way? I'm hoping for less code. Also, I'd expect to be able to extract the primary key of every entity, as I attempt in .getId().

like image 276
simpatico Avatar asked Jul 25 '10 10:07

simpatico


People also ask

How do we mention primary key in JPA entity?

In JPA, we have two options to define the composite keys: the @IdClass and @EmbeddedId annotations. In order to define the composite primary keys, we should follow some rules: The composite primary key class must be public. It must have a no-arg constructor.

What does @ID do in JPA?

@Id will only declare the primary key. it will not insert generated value. if you use @GeneratedValue then it will generate the value of the field.

Which annotation is used to define primary key of an entity class?

Simple primary keys use the javax.persistence.Id annotation to denote the primary key property or field.

Which method in JPA is used to retrieve the entity based on its primary keys?

Retrieval by Query The most flexible method for retrieving objects from the database is to use queries. The official query language of JPA is JPQL (Java Persistence Query Language).


2 Answers

This functionality was added in JPA 2.0. Simply call:

Object id = entityManagerFactory.getPersistenceUnitUtil().getIdentifier(entity);
like image 118
Gordon Yorke Avatar answered Oct 10 '22 10:10

Gordon Yorke


Read an article about Generic Dao approach.

I don't clearly understand your problem, but if you want to get entity id - just get it. Its available after persist method is complete i.e.

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

I usually make a class AbstractEntity with field id and its accessors and inherit all my other entities from this class.

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

like image 34
Roman Avatar answered Oct 10 '22 11:10

Roman