mod
mod

Reputation: 383

one to multiple many relationship

Consider two tables as mentioned below -
Table1 (id_col, name_col)
Table2 (uid_col, code_col_1, code_col_2)

where,
id_col is primary key for Table1
uid_col is primary key for Table2
and, id_col has one to many relationship with both code_col_1 and code_col_2

Records could look like:-
Table1
1, xxx
2, yyy

Table2
11, 1, 2
12, 2, 1
12, 2, 2

How will the JPA look like in following classes?

@Entity
@Table(name = "Table1")
public class T1 {
    @OneToMany(targetEntity=T2.class, mappedBy="??????", cascade=CascadeType.ALL)
    private List<T2> t2; //???not sure about this
}

@Entity
@Table(name = "Table2")
public class T2 {
    @ManyToOne
    @JoinColumn(name="code_col_1")
    private T1 t1;  //???not sure what goes here
}

Upvotes: 3

Views: 596

Answers (1)

ChssPly76
ChssPly76

Reputation: 100776

This is not a one-to-many association; rather, it's two separate many-to-one associations from T2 to T1. You'd map both on T2 side:

@Entity
@Table(name = "Table2")
public class T2 {
  @Id // map whatever generator you'd like
  private long id;

  @ManyToOne
  @JoinColumn(name="code_col_1")
  private T1 t1_code1;

  @ManyToOne
  @JoinColumn(name="code_col_2")
  private T1 t1_code2;
}

Mapping the reverse one-to-many associations from T1 to T2 is not a good idea because you risk having (some of) the same elements in both collections which will result in all sorts of troubles during inserts / deletes.

Upvotes: 1

Related Questions