Hibernate a bidirectional one-to-one association on a foreign key
Use hibernate create bidirectional one-to-one asscocition on a foreign .
The tables' structural is the same as unidirectional one-to-one association on a foreign key tables.
But, the application code is not the same as that.
Unidirectional one-to-one assciation is a table association another Unidirectional. It means you can find data by foreign key use a table but can
not use another table do it too.
For example also husband and wife:
When husband and wife is association on a foreign key unidirectional. And you set the foreign key in husband table. You can find wife by foreign key.
Because the wife has no column injo. You can not fint husband from wife (so this women lost her husband <just play a joke!>).
When husband and wife is association on a foreign key bidirectional. And you set the foreign key in both them. you can find data each other.
So, How to do it?
It's just a little diffrience with bidirectional one-to-one association on a foreign key :
The object Husband:
1 package com.hibernate.model; 2 3 import javax.persistence.Entity; 4 import javax.persistence.GeneratedValue; 5 import javax.persistence.Id; 6 import javax.persistence.JoinColumn; 7 import javax.persistence.OneToOne; 8 9 @Entity 10 public class Husband { 11 private int id; 12 private String name; 13 private Wife wife; 14 @Id 15 @GeneratedValue 16 public int getId() { 17 return id; 18 } 19 public void setId(int id) { 20 this.id = id; 21 } 22 public String getName() { 23 return name; 24 } 25 public void setName(String name) { 26 this.name = name; 27 } 28 @OneToOne 29 @JoinColumn(name="wifeId") 30 public Wife getWife() { 31 return wife; 32 } 33 public void setWife(Wife wife) { 34 this.wife = wife; 35 } 36 }
The Object Wife:
1 package com.hibernate.model; 2 3 import javax.persistence.Entity; 4 import javax.persistence.GeneratedValue; 5 import javax.persistence.Id; 6 import javax.persistence.JoinColumn; 7 import javax.persistence.OneToOne; 8 9 @Entity 10 public class Wife { 11 private int id; 12 private String name; 13 private Husband hasband; 14 @Id 15 @GeneratedValue 16 public int getId() { 17 return id; 18 } 19 public void setId(int id) { 20 this.id = id; 21 } 22 public String getName() { 23 return name; 24 } 25 public void setName(String name) { 26 this.name = name; 27 } 28 @OneToOne(mappedBy="wife") 29 public Husband getHasband() { 30 return hasband; 31 } 32 public void setHasband(Husband hasband) { 33 this.hasband = hasband; 34 } 35 }
It just add the @OneToOne(mappedBy="wife")
It means the one-to-one mapped by wife, the wife is the husband object geted wife.
MappedBy() method in java EE API:
public abstract java.lang.String mappedBy
- (Optional) The field that owns the relationship. This element is only specified on the inverse (non-owning) side of the association.
From API's description, We can know Husband owns the relationship. Wife is on the inverse side.
so mappedBy must add In Wife.
浙公网安备 33010602011771号