views:

48

answers:

3

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().

A: 

The common interface approach is what I use and it works fine. Using pure JPA I don't see a way of getting the identifier.

Have a look at merge(). I've not used it much myself but I think

Hibernate has ways of doing this

Serializable id = session.getIdentifier(entity);

But this is not JPA standard.

Mike Q
A: 

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.

Roman
+2  A: 

This functionality was added in JPA 2.0. Simply call:

Object id = entityManagerFactory.getPersistenceUnitUtil().getIdentifier(entity);

Gordon Yorke