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().
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.
@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.
Simple primary keys use the javax.persistence.Id annotation to denote the primary key property or field.
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).
This functionality was added in JPA 2.0. Simply call:
Object id = entityManagerFactory.getPersistenceUnitUtil().getIdentifier(entity);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With