使用ManyToOne关系定义创建复合ID

时间:2015-01-22 16:09:43

标签: java hibernate many-to-one

Hibernate需要我的实体ID:

(throws org.hibernate.AnnotationException:没有为实体指定标识符

@Entity
@Table(name = "CHILDREN")
public class ChildDb {

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "INNER_ID", nullable = false)
    private ParentDb parent;

    @Column(name = "NAME")
    private String name;

    @Column(name = "VALUE")
    private double value;
}

这里是父实体:

@Entity
@Table(name = "PARENT")
public class ParentDb {
    @Id
    @Column(name = "INNER_ID")
    @GeneratedValue(strategy = GenerationType.AUTO, generator = "G1")
    @SequenceGenerator(name = "G1", sequenceName = "SOME_SEQ")
    private long id;

    @Column(name = "TIMESTAMP")
    private long timestamp;

    @OneToMany(fetch = FetchType.EAGER, mappedBy = "parent", cascade = {CascadeType.ALL}, orphanRemoval=true)
    private List<ChildDb> children;
}

但是,id应该是复合的 - 父ID和名称。

如何定义?

2 个答案:

答案 0 :(得分:0)

我相信这样做会有效:

@Entity
@Table(name = "CHILDREN")
public class ChildDb implements Serializable{

@Id
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "INNER_ID", nullable = false)
private ParentDb parent;

@Id
@Column(name = "NAME")
private String name;

@Column(name = "VALUE")
private double value;

}

答案 1 :(得分:0)

在我看来,你做的奇怪的事情可能就是这样:

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "INNER_ID", nullable = false)
private ParentDb parent;

您的ChildDB中是否还有“INNER_ID”。如果是OneToMany关系,@ ManyToOne方必须是外键的所有者。