JPA onetone embeddedid

时间:2015-03-24 16:49:10

标签: jpa composite-primary-key

我正在JPA中建立一个关系,我可以将文件拆分成多个文件,同时在关联表中保持原始文件关系。 我有MyFile实体和FileRelationship实体,它是具有两列的关联表:myFileId(primary-key),parentId)。这两列是引用MyFile id的外键。

所以我有两个实体,MyFile.java和FileRelationship.java。 MyFile可以有一个父级,父级可以有多个子级。该关系存储在FileRelationship表中。


MyFile.java

@Entity
public class MyFile implements Cloneable {  
    @Id
    @SequenceGenerator(name="MYFILE_SEQ", sequenceName="MYFILE_SEQ", allocationSize=1)
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="MYFILE_SEQ")
    private Long id;

    //get the parent in the fileRealtionship for this MyFile
    @OneToOne (mappedBy="myFile")
    private FileRelationship fileRelationship;
    ...
}


FileRelationship.java

@Entity
public class FileRelationship implements Serializable {     
    @EmbeddedId
    private MyFileId id;

    @MapsId("myFileId") 
    @OneToOne()
    @JoinColumn(name="myFileId")
    private MyFile myFile;

    @ManyToOne
    @JoinColumn(name="parentId")
    private MyFile parent;
    ...
}


MyFileId.java

@Embeddable
public class MyFileId implements Serializable {
    private Long myFileId;

    public MyFileId() {
        super();
    }

    public MyFileId(Long myFileId) {
        super();
        this.myFileId = myFileId;
    }

    public Long getMyFileId() {
        return myFileId;
    }
    ...
}

当我尝试存储关系时,我无法保存关系。我一直在

  

org.hibernate.AssertionFailure:null identifier

如果我将FileRelationship.java中的以下内容更改为ManyToOne,那么它可以正常工作:

@MapsId("myFileId") 
@ManyToOne  //@OneToOne()
@JoinColumn(name="myFileId")
private MyFile myFile;

但是这意味着很多FileRelationship实体可以属于一个myFile实体,这意味着myFile不再是主键。

0 个答案:

没有答案