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

Categories

0 votes
266 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

This functionality was added in JPA 2.0. Simply call:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...