持久化JPA对象时映射错误

时间:2014-11-05 02:12:35

标签: java jpa eclipselink

我在一周内遇到了这个错误。 任何人都可以解释为什么我会收到此错误以及如何解决此问题?

我有一个Entiry类版本,我希望在保留Version实体对象后返回Id。但是我收到了这个错误:

Exception [EclipseLink-71] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: A NullPointerException was thrown while setting the value of the instance variable [id] to the value [38].
Internal Exception: java.lang.NullPointerException
Mapping: org.eclipse.persistence.mappings.DirectToFieldMapping[id-->Version.ID]
Descriptor: RelationalDescriptor(varick.rap.demo.entities.VersionPK --> [DatabaseTable(Version)])

这是我的完整代码:

    factory = Persistence.createEntityManagerFactory(PERSISTENCE_NAME);
    entity = factory.createEntityManager();
    entity.getTransaction().begin();

    Version version = new Version();
    version.setVersion(getNext(this.version));
    version.setProjectID(projectID);
    entity.persist(version);
    entity.flush();
    System.out.println("Version Id: " + version.getId());
    entity.getTransaction().commit();

版本实体类(此类使用@EmbeddedId):

@Entity
@Table(name="Version")
public class Version implements Serializable {
    @EmbeddedId 
    private VersionPK id;

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

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

    public Version() {
    }

    public VersionPK getId() {
        return this.id;
    }
    //get and set methods here

VersionPK类:

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

    @Column(name="ID")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int id;

    public VersionPK() {
    }
    //get and set method here

1 个答案:

答案 0 :(得分:0)

未设置主键。也许你应该这样做:

VersionPK pk = new VersionPK();
pk.setId("****");

Version version = new Version();
version.setId(pk);
version.setVersion(getNext(this.version));
version.setProjectID(projectID);
entity.persist(version);
entity.flush();
System.out.println("Version Id: " + version.getId());
entity.getTransaction().commit();