@onetoone和@EmbeddedId

时间:2011-09-17 21:09:56

标签: java hibernate

我正在尝试在类之间创建一对一的关系,让我们先调用它,然后让另一个调用它。

如果第二类使用@EmbeddedId作为主键,它不允许我这样做,我该如何解决这个问题呢?

基本上结构如下:

@Entity
class First {
     private Integer id;
     private Second second;

     @OneToOne
     @JoinColumn(name="id",  referencedColumnName="parentId", nullable=true)        
     public Second getSecond() {return second;}
     ... snip irrelevant methods ...
}

@Entity
class Second{
     private Integer id;
     private Integer parentId;
     ... snip irrelevant methods ...
}

以上工作正常,但如果我将其更改为

@Entity
class Second{
     private MyCustomKey key;
     private Integer parentId;
     ... snip irrelevant methods ...
}

我收到“Broken mapping”错误。

我没有看到差异,因为两个ID都是手动分配的?具有整数id的工作版本和嵌入式id。

1 个答案:

答案 0 :(得分:1)

以下代码适用于我。

第一个实体

@Entity
public class Ent1 implements Serializable {

    private static final long serialVersionUID = -5580880562659281420L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    public void setId(Integer id) {
        this.id = id;
    }

    public void setA(Integer a) {
        this.a = a;
    }

    private Integer a;

    @OneToOne
    @JoinColumn(name="second",  referencedColumnName="parentId", nullable=true) 
    private Ent2 second;

    public void setSecond(Ent2 second) {
        this.second = second;
    }
}

第二个实体类(使用复合PK)

@Entity
public class Ent2 implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = -1554968351865549494L;

    @EmbeddedId
    private Ent2Id id;

    public Ent2Id getId() {
        return id;
    }

    public void setId(Ent2Id id) {
        this.id = id;
    }

    public Integer getParentId() {
        return parentId;
    }

    public void setParentId(Integer parentId) {
        this.parentId = parentId;
    }

    Integer parentId;
}

我的自定义密钥类

@Embeddable
public class Ent2Id implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 3000940427471306899L;

    Integer eid1 = 0;
    Integer eid2 = 1;

    public Ent2Id() {

    }

    public Ent2Id(Integer a, Integer b) {
        eid1 = a;
        eid2 = b;
    }
}