I just want to answer the third question because it's not fully explained.
Here is your question:
Why does the husband member alone have @OnetoOne(mappedBy="Wife"), but the wife member does not have @OnetoOne(mappedBy="husband")
First, there is something wrong here: it should be:
@OneToOne(mappedBy="wife")
, not Wife
. Note that mappedBy
should be followed by the attribute wife
of the Husband
class, not the class Wife
, neither the Husband
class name, although the Husband
class is the owner. In the document of Hibernate is said:
mappedBy refers to the property name of the association on the owner side.
Second, one thing to have in mind is, there are two kinds of relationship when we do the database mapping: unidirectional and bidirectional. We use unidirectional relationship, when we only want one part handle/maintain this relationship, but from the other side, we are not interested in getting the data of this side. In your example, if we just want an unidirectional relationship from Husband
to Wife
class, we only want to know, by having an object of type Husband
, who is his wife(by its getWife()
method), but we are not interested in knowing one lady's husband.
Under this circumstance, we can code like this:
(note that in class Husband
we have attribute of Wife
type, but in Wife
class we don't have attribute of Husband
type)
Husband.java:
@Entity
public class Husband implements Serializable {
...
@OneToOne
//note that @JoinColumn is necessary when mapping,
//and although in the table you may have columns like
//`ID_WIFE` in table of Husband, in Java it's not a number
//attribute, it's an attribute of `Wife` type.
@JoinColumn(name="idWife")
private Wife wife;
}
Wife.java:
@Entity
public class Wife implements Serializable {
@Id
private int id;
private String name;
//We can omit the attribute `husband` of `Husband` type,
//because we are not interested in it. Or, we don't need
//to map in the owned side, because it's unidirectional.
}
But, if we want to have an bidirectional relationship, we have to map in both side and in the owned side, mappedBy
is needed before the attribute owned.
We remain the Husband
side intact, and we change the Wife.java
:
Wife.java:
@Entity
public class Wife implements Serializable {
@Id
private int id;
private String name;
@OneToOne(fetch=FetchType.LAZY, mappedBy="wife")
private Husband husband;
}
Check this page: https://en.wikibooks.org/wiki/Java_Persistence/OneToOne, it explains it all in an understandable way.
Third, just a little note: the owner side, is commonly the class of a table with a FK of another table. Or, we just remember: the owner owns it all, so it also has the FK in its table.