帮助在JPA 2.0中映射复合外键

时间:2011-04-19 19:22:52

标签: orm jpa

我是JPA的新手,我正在尝试映射旧数据库。文件单独正确加载但关系无法正常工作。任何帮助将不胜感激。

爪哇

@Entity
@IdClass(ParentKey.class)
public class Parent {
    @Id
    @Column(name="code")
    private String code;

    @Id
    @Column(name="id")
    private int id;

    @OneToMany(mappedBy="parent")
    private List<Child> children = new ArrayList<Child>();
}

public class ParentKey {
    private String code;
    private int id;
}

@Entity
@IdClass(ChildKey.class)
public class Child {
    @Id
    @JoinColumns({
        @JoinColumn(name="code")
        @JoinColumn(name="id")
    })
    private Parent parent;

    @Id
    @Column(name="index")
    private int index;
}

public class ChildKey {
    private String code;
    private int id;
    private int index;
}

SQL

create table Parent(
  code char(4) not null,
  id int not null,
  primary key(code,id)
);

create table Child(
  code char(4) not null,
  id int not null,
  index int not null,
  primary key(code, id, index),
  foreign key(code, id) references Parent(code,id)
);

编辑1: 添加ChildKey和ParentKey类。

3 个答案:

答案 0 :(得分:2)

这是一个指向化合物身份1-N关系的DataNucleus文档的链接。可以帮助您找出问题所在。首先,您没有在Child上定义IdClass

http://www.datanucleus.org/products/accessplatform_3_0/jpa/orm/compound_identity.html#1_N_coll_bi

答案 1 :(得分:2)

以下是OpenJPA使用其ReverseMapping Tool创建的内容,它似乎正常工作。

@Entity
@Table(name="PARENT")
@IdClass(ParentId.class)
public class Parent {
  @OneToMany(targetEntity=Child.class, mappedBy="parent", cascade=CascadeType.MERGE)
  private Set childs = new HashSet();

  @Id
  @Column(length=4)
  private String code;

  @Id
  private int id;

  //omitted getters, setters
}

public class ParentId implements Serializable {
  public String code;
  public int id;

  //omitted getters, setters, toString, equals, hashcode
}

@Entity
@Table(name="CHILD")
@IdClass(ChildId.class)
public class Child {
  @Id
  @Column(length=4)
  private String code;

  @Id
  private int id;

  @Id
  private int index;

  @ManyToOne(fetch=FetchType.LAZY, cascade=CascadeType.MERGE)
  @JoinColumns({@JoinColumn(name="code"), @JoinColumn(name="id")})
  private Parent parent;

  //omitted getters, setters
}

public class ChildId implements Serializable {
  public String code;
  public int id;
  public int index;

  //omitted getters, setters, toString, equals, hashcode
}

答案 2 :(得分:0)