如何在提交事务后从实体对象获取ID(PRIMARY KEY)?

时间:2014-11-03 10:08:11

标签: java jpa eclipselink jpa-2.0

我坚持一个对象并像这样提交:

        Version version = new Version();
        version.setVersion(getNext(this.version));
        version.setProjectID(projectID);
        em.persist(version);
        em.getTransaction().commit();

我希望通过以下代码行获取ID(主键):

Object id = factory.getPersistenceUnitUtil().getIdentifier(version);

我可以获得VersionProjectID,但ID null 。 ID是自动生成的,但仍返回null。我试图在我的实体类中实现@GeneratedValue(strategy=GenerationType.IDENTITY)但没有任何改变。对我来说有什么解决方案吗?

使用更多代码进行编辑

版本实体:这是使用EmbededId

    @Entity
    @NamedQuery(name="Version.findAll", query="SELECT v FROM Version v")
    @Table(name="Version")
    public class Version implements Serializable {    

    @EmbeddedId
    @GeneratedValue(strategy=GenerationType.SEQUENCE)
    private VersionPK id;

    @Column(name="Version")
    private String version;

    @Column(name="ProjectID")
    private int projectID;

可嵌入课程:

    @Embeddable
    public class VersionPK implements Serializable {
    //default serial version id, required for serializable classes.
    private static final long serialVersionUID = 1L;

    @Column(name="ID")
    private int id;

    public VersionPK() {
    }

1 个答案:

答案 0 :(得分:0)

您必须在承诺能够获得flush()之后使用id

em.persist(version);
em.getTransaction().commit();
em.flush();

然后使用getter获取id:

Object id = version.getId();//getId() is the getter of the id in your entity.

See the answer here