@ManyToOne和@OneToOne与@EmbeddedId的关系

时间:2014-08-12 13:01:21

标签: java sql database jpa one-to-many

我正在尝试将数据库实体的id从单个long更改为由两个long组成的复合id,这两个long被封装在我的ID.class中,如下所示。你会对ManyToOne和OneToMany关系使用什么注释?我的注释是否犯了错误,尤其是@JoinColumns,@ Embeddable和@EmbeddedId。我的问题是关系存储为null;

我的ID类由自动生成的long(pid)和手动设置的secondary long(sid)组成。这是我所有实体类的ID:

@Embeddable
public class ID implements Serializable {

    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private long pid;
    @Column(nullable=false)
    private long sid;
}

My Entity-class(示例)与Office的多对一​​关系与Settings的一对一关系(两种关系都是单向的)。

@Entity
@Table(name="user")
public class User {

    @EmbeddedId
    private ID id;

    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumns({
        @JoinColumn(name = "office_pid", referencedColumnName = "pid", updatable=false, insertable=false),
        @JoinColumn(name = "office_sid", referencedColumnName = "sid", updatable=false, insertable=false)
    })
    private Office office;

    @OneToOne(cascade={CascadeType.PERSIST, CascadeType.REMOVE}, fetch=FetchType.LAZY)
    @JoinColumns({
        @JoinColumn(name = "setting_pid", referencedColumnName = "pid", updatable=false, insertable=false),
        @JoinColumn(name = "setting_sid", referencedColumnName = "sid", updatable=false, insertable=false)
    })
    private Settings setting;

    @OneToMany(mappedBy = "user", cascade=CascadeType.REMOVE, fetch=FetchType.LAZY)
    private List<Account> accounts= new ArrayList<>();
}

Office类(多对一示例):

@Entity
@Table(name = "office")
public class Office {

    @EmbeddedId
    private ID id;
    @Column(length = 128)
    private String description;

}

帐户类(一对多示例):

@Entity
@Table(name="account")
public class Account {

    @EmbeddedId
    private ID id;
    @Column(length = 16)
    private String description;

    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumns({
        @JoinColumn(name = "user_pid", referencedColumnName = "pid"),
        @JoinColumn(name = "user_sid", referencedColumnName = "sid")
    })
    private User user;
}

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

如果您需要复合pk,则不应使用排序 - 仅使用唯一的序列生成字段或唯一的复合业务字段。

第二个问题是User中的joinColumn定义。您已将它们标记为updatable = false,insertable = false这意味着无法通过映射更改外键,并且无论设置关系如何,它们始终为null。从每个设置中删除updatable = false,insertable = false设置,以便在设置关系时设置字段。