Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA Child Class Referenced By Multiple Different Parent Classes

Tags:

java

orm

jpa

I met the following ORM problem:

I am having two classes A and B who both are having a Set of class C:

class A {
  @Id
  @GeneratedValue
  private long id;

  @OneToMany
  private Set<C> cSet;
}

class B {
  @Id
  @GeneratedValue
  private long id;

  @OneToMany
  private Set<C> cSet;
}

class C {
  @Id
  @GeneratedValue
  private long id;
}

One idea I had was using a MappedSuperclass for C and having two extended classes that are each referenced in either A or B. But from an object oriented point of view this is not the nicest approach although I could use the superclass type in order to work with them.

Is there any nicer way to realize this model?

Thanks, Benjamin

like image 483
Benjamin Ihrig Avatar asked Feb 18 '23 03:02

Benjamin Ihrig


1 Answers

If you don't specify any mapping annotation (i.e. JoinColumn or JoinTable), it will use a join table for each association.

You will thus have the following tables:

A : id
B : id
C : id
A_C : a_id, c_id (where c_id is unique)
B_C : a_id, c_id (where c_id is unique)

The alternative if to annotate each set with a JoinColumn annotation:

class A {
    @OneToMany
    @JoinColumn(name = "a_id")
    private Set<C> cSet;
}

class B {
   @OneToMany
   @JoinColumn(name = "b_id")
   private Set<C> cSet;
}

And you will thus have the following tables:

A : id
B : id
C : id, a_id, b_id

This is of course described in the documentation.

like image 115
JB Nizet Avatar answered Apr 28 '23 06:04

JB Nizet