JPA @OneToMany
By Ariel Luduena Karhs
Suppose you have this two entities: PhoneList and Phone.
PhoneList have a @OneToMany to Phone. (I need only a unidirectional relationship)
Something like:
1 2 3 4 |
@OneToMany(cascade=CascadeType.ALL) public List<Phone> getPhones() { return phones; } |
The phone entity doesn’t have nothing special.
If you deploy those entities your JPA provider will create 3 tables. One table for each entity and also a “JoinTable”. But, why? This kind of relationship can be done by 2 tables only and I don’t want a third table. I want a PHONE table with an FK column to PHONELIST table.
How can I do that?
Two options:
- Make your relationship bidirectional
- Add an @JoinColumn in the @OneToMany attribute
Option number 1 – Make your relationship bidirectional
The problem is that “I don’t need a bidirectional relationship”! … Ok, but, suppose that you are more interested in solve this and move forward to a “real issue”.
To make this relationship bidirectional, you must add in the Phone entity the reference to the PhoneList entity with the @ManyToOne annotation. Something like:
1 2 3 4 5 6 7 8 9 10 11 12 |
@Entity public class Phone { private Long id; private String phoneNumber; private PhoneList phoneList; @ManyToOne public PhoneList getPhoneList() { return phoneList; } ... |
Also you have to add to the relationship @OneToMany in the PhoneList entity the mapped by attribute. Something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
@Entity public class PhoneList { private Long id; private String name; private String description; private List<Phone> phones; @Id @GeneratedValue public Long getId() { return id; } public void setId(Long id) { this.id = id; } @OneToMany(cascade=CascadeType.ALL, mappedBy="phoneList") public List<Phone> getPhones() { return phones; } |
Option number 2 – Add @JoinColumn in the @OneToMany attribute
If you don’t want to have a bidirectional relationship, you have to use @JoinColumn like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
@Entity public class PhoneList { private Long id; private String name; private String description; private List phones; @Id @GeneratedValue public Long getId() { return id; } public void setId(Long id) { this.id = id; } @OneToMany(cascade=CascadeType.ALL) @JoinColumn(name="phone_list_id", referencedColumnName="id") public List getPhones() { return phones; } |
and the Phone entity remain without references
1 2 3 4 5 6 7 |
@Entity public class Phone { private Long id; private String phoneNumber; ... |