@OneToOne是Hibernate中常见的表关系注解,指两张表是一对一的关系。
可以有一对一单向,一对一双向,同时又可以有外键关联和主键关联,总共4种。
用丈夫表和妻子表(想做@OneToMany的可以自己试试,括弧笑)举个一对一双向外键关联的例子:
创建数据表,当然你也可以让hibernate帮你生成。效果如下
CREATE TABLE `husband` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`wife_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `FK4BB1A83BA5D21E37` (`wife_id`),
CONSTRAINT `FK4BB1A83BA5D21E37` FOREIGN KEY (`wife_id`) REFERENCES `wife` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
CREATE TABLE `wife` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
创建wife,husband类,并注解。
如果在wife内的@OneToOne(mappedBy = “wife”)中不加mappedBy,你会发现运行hibernate后wife里也会生成一个husband_id的外键指向husband表。
mappedBy后的wife是指husband类中的wife对象
@Entity
public class wife
{
private int id;
private String name;
private husband husband;
@Id
@GeneratedValue
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
@OneToOne(mappedBy = "wife")
public husband getHusband()
{
return husband;
}
public void setHusband(husband husband)
{
this.husband = husband;
}
}
@Entity
public class husband
{
private int id;
private String name;
private wife wife;
@Id
@GeneratedValue
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
@OneToOne
public wife getWife()
{
return wife;
}
public void setWife(wife wife)
{
this.wife = wife;
}
}