0

After I persist an object and commit like this:

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

I want to get the ID(Primary Key) by this code line:

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

I can get the Version and ProjectID but the ID is null. The ID is auto generated but still return null. I tried to implement @GeneratedValue(strategy=GenerationType.IDENTITY) in my entity class but nothing change. Any solution for me?

EDIT WITH MORE CODE

Version Entity: this is using an 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 class:

    @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() {
    }
gamo
  • 1,549
  • 7
  • 24
  • 36
  • I'm not quite sure if I understand you correctly, but you might have a look at the `@id` annotation from JPA2. Maybe that solves your problem. – L.Butz Nov 03 '14 at 10:18
  • 1
    maybe showing people your actual class may help? – Neil Stockton Nov 03 '14 at 10:24
  • I think the problem is because that entity object cannot get the auto generate ID from database. Method `version.getId()` always return null but `version.getVersion` and `version.getProjectID` is working well. – gamo Nov 04 '14 at 04:02

1 Answers1

0

You have to use flush() after commiting to be able to get the id:

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

Then just use getter to have the id:

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

See the answer here.

Community
  • 1
  • 1
cнŝdk
  • 31,391
  • 7
  • 56
  • 78