Hibernate 系列教程7-双向一对一
双向一对一
一对一主要用在
一个一方需要的信息比较少,比如注册的登录信息
另一个一方存储的信息比较多,比如注册之后用户填写的详细信息
实现方式常用的主要有2种:
java模型都是一样,其中一个映射文件有所不同
hibernate.cfg.xml
<mapping resource="com/jege/hibernate/two/way/onetoone/User.hbm.xml" />
<mapping resource="com/jege/hibernate/two/way/onetoone/UserInfo.hbm.xml" />
User
//主一
public class User {
private Long id;
private String username;
private String password;
private UserInfo info;
UserInfo
//从一
public class UserInfo {
private Long id;
private Integer age;
private String address;
private User user;
User.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.jege.hibernate.two.way.onetoone">
<class name="User" table="t_user">
<id name="id">
<generator class="native" />
</id>
<property name="username" />
<property name="password" />
<one-to-one name="info" class="UserInfo" />
</class>
</hibernate-mapping>
模拟外键一对一UserInfo.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.jege.hibernate.two.way.onetoone">
<class name="UserInfo" table="t_user_info">
<id name="id">
<generator class="native" />
</id>
<property name="age" />
<property name="address" />
<!-- 使用多对一的方式来模拟一对一的关系 -->
<!-- unique="true"外键的唯一 -->
<many-to-one name="user" class="User" column="user_id" unique="true" />
</class>
</hibernate-mapping>
CREATE TABLE `t_user_info` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`age` int(11) DEFAULT NULL,
`address` varchar(255) DEFAULT NULL,
`user_id` bigint(20) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `UK_ln50dwtk2w5skl1rpjfek5srv` (`user_id`),
CONSTRAINT `FK_ln50dwtk2w5skl1rpjfek5srv` FOREIGN KEY (`user_id`) REFERENCES `t_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
共享主键一对一
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.jege.hibernate.two.way.onetoone">
<class name="UserInfo" table="t_user_info">
<id name="id">
<generator class="foreign">
<!-- UserInfo的主键来自于当前user属性的id -->
<param name="property">user</param>
</generator>
</id>
<property name="age" />
<property name="address" />
<!-- 共享主键是关系双方的主键是一样的值 -->
<!-- constrained="true"添加约束的关键 -->
<one-to-one name="user" constrained="true" />
</class>
</hibernate-mapping>
CREATE TABLE `t_user_info` (
`id` bigint(20) NOT NULL,
`age` int(11) DEFAULT NULL,
`address` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `FK_ihje4vsyvt8vmuhru59ib9j1d` FOREIGN KEY (`id`) REFERENCES `t_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
还有一种可以使用多一张中间表,设置主键唯一,外键同时唯一的方式,不过基本没有使用场景。
源码地址
https://github.com/je-ge/hibernate
如果觉得我的文章对您有帮助,请予以打赏。您的支持将鼓励我继续创作!谢谢!