at sometime we usually need to create two tables that one table relate another.Such as a husband only
have a wife. So how can I design relationship like this.In programming, The type of this relationship
named “unidirectional one-to-one association”.
How to implement this relationship with hibernate?
example for husband and wife.
When create object husband and wife, you can relate two object like this:
The Hasband object:
1: @Entity
2: public class Husband {
3: private int id;
4: private String name;
5: private Wife wife;
6: @Id
7: @GeneratedValue
8: public int getId() {
9: return id;
10: }
11: public void setId(int id) {
12: this.id = id;
13: }
14: public String getName() {
15: return name;
16: }
17: public void setName(String name) {
18: this.name = name;
19: }
20: @OneToOne
21: @JoinColumn(name="wifeId")
22: public Wife getWife() {
23: return wife;
24: }
25: public void setWife(Wife wife) {
26: this.wife = wife;
27: }
28: }
The Wife object:
1: @Entity
2: public class Wife {
3: private int id;
4: private String name;
5: @Id
6: @GeneratedValue
7: public int getId() {
8: return id;
9: }
10: public void setId(int id) {
11: this.id = id;
12: }
13: public String getName() {
14: return name;
15: }
16: public void setName(String name) {
17: this.name = name;
18: }
19:
20: }
We use annotation configuration hibernate by default. So you saw the annotition like @Entity in code.
Wife and Husband both are used @Entity.It means that object will mapping to database.
The getId() method in Wife and Husband both are used @Id and @GeneratedValue
The getWife() method in Husband object has annotation like this:
@OneToOne
@JoinColumn(name="wifeId")
Then, the column which is named wifeId wille be created.
So, Use annotation is so simple. that;s all.
Do from that we can get create table SQL like this:
1: create table Husband (
2: id integer not null auto_increment,
3: name varchar(255),
4: wifeId integer,
5: primary key (id)
6: )
7: 2014-1-11 14:46:41 org.hibernate.tool.hbm2ddl.SchemaExport perform
8:
9:
10: create table Wife (
11: id integer not null auto_increment,
12: name varchar(255),
13: primary key (id)
14: )
15:
16: alter table Husband
17: add constraint FK_kruq9jfxa0jrc2od8dbh09mia
18: foreign key (wifeId)
19: references Wife (id)
Finally , Talk about xml configure. When use xml to configure hibernate more trouble than use annotations:
You need write like this in xml file:
<many-to-one name="wife" column="wifId" unique="true" ></many-to-one>