使用多个主键(可嵌入类)持久化JPA类时出错

时间:2014-03-08 16:04:16

标签: java-ee jpa persistence

我有一个带有2 PK的表的数据库。

我开发了JPA类

@Entity
@NamedQuery(name="Drive.findAll", query="SELECT d FROM Drive d")
public class Drive implements Serializable {
    private static final long serialVersionUID = 1L;

    @EmbeddedId
    private DrivePK id;

    @ManyToOne
    @JoinColumn(name="id_content")
    private Content content;

    @ManyToOne
    @JoinColumn(name="id_user")
    private User user;

    public Drive() {
    }

    public Drive(Content content, User user) {
        this.content = content;
        this.user = user;
        this.id = new DrivePK(user.getId(), content.getId());
    }

    // + getters/setters user + content + drivePK
}

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

    @Column(name="id_user", insertable=false, updatable=false)
    private int idUser;

    @Column(name="id_content", insertable=false, updatable=false)
    private int idContent;

    public DrivePK() {
    }

    public DrivePK(int idUser, int idContent) {
        this.idUser = idUser;
        this.idContent = idContent;
    }

    // + getters/setters idUser and idContent
}

当我尝试坚持像这样的驱动对象时

Drive drive = new Drive(content, user);
em.create(drive); //after injection

我收到此错误

Avertissement: Unexpected exception from beforeCompletion; transaction will roll back
<openjpa-2.3.0-nonfinal-1540826-r422266:1542644 fatal general error> org.apache.openjpa.persistence.PersistenceException: The transaction has been rolled back. See the nested exceptions for details on the errors that occurred.
    at org.apache.openjpa.kernel.BrokerImpl.newFlushException(BrokerImpl.java:2370)
    ...
Caused by: <openjpa-2.3.0-nonfinal-1540826-r422266:1542644 nonfatal user error> org.apache.openjpa.persistence.ArgumentException: Field "jpa.Drive.id" of "jpa.Drive@85094f" can not be set to "jpa.DrivePK@4bbe" value.

我知道错误与DrivePK有关但我不知道什么是不正确的。

1 个答案:

答案 0 :(得分:1)

我很确定问题是由PK列上的insertable=false属性引起的 - 您试图插入一个您认为不可插入的值。

我相信updatable=false没问题(您不希望更新PK字段),但如果它仍然无效,请尝试删除它。

相关问题