Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Help Mapping a Composite Foreign Key in JPA 2.0

Tags:

orm

jpa

I'm new to JPA and I'm trying to map a legacy database. The files load correctly individually but the relationships are not working correctly. Any help would be appreciated.

Java

@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)
);

edit 1: add the ChildKey and ParentKey classes.

like image 958
Jared Pearson Avatar asked Apr 19 '11 19:04

Jared Pearson


1 Answers

Here's a link to DataNucleus docs for compound identity 1-N relation. May help you identify what is wrong. For a start you have no IdClass defined on Child

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

like image 110
DataNucleus Avatar answered Oct 31 '22 12:10

DataNucleus