JPA / Hibernate使用依赖于Parent的Composite Key保存子级

时间:2012-01-19 19:23:00

标签: hibernate jpa

我正在寻找一种方法来保存数据库生成Id(@GeneratedValue)的位置,并将该值级联到作为Composite Key一部分的子对象。假设我们有以下Parent

@Entity
@Table("PARENT")
public class Parent {

    private long id;
    private List<Child> children;

    @Id
    @GeneratedValue
    @Column(name="...")
    public long getId() {
        return this.id
    }

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

    @OneToMany(mappedBy="key.parent", cascade= { CascadeType.ALL })
    public List<Child> getChildren() {
        return this.children;
    }
}

带孩子:

@Entity
@Table("CHILD")
public class Child {
    private CompositeKey key;
    private String value;

    @EmbeddedId
    public CompositeKey getKey() {
        return this.key
    }

    public void setKey(CompositeKey key) {
        this.key = key;
    }

    // .. basic mapping of value column

}

和复合键:

@Embeddable
public class CompositeKey key {
    private String type;
    private Parent parent;

    @Column(name="TYPE")
    public String getType() {
        return this.type;
    }

    public void setType(String type) {
        this.type = type;
    }

    @ManyToOne
    @JoinColumn("PARENT_ID") // FK in the Child table
    public Parent getParent() {
        return this.parent;
    }

    public void setParent(Parent parent) {
        this.parent = parent;
    }
}

有人知道这可以如何运作,Parent的ID可以作为Child

的一部分保存并设置为CompositeKey中FK的一部分

0 个答案:

没有答案
相关问题