Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
265 views
Welcome To Ask or Share your Answers For Others

1 Answer

This functionality was added in JPA 2.0. Simply call:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...