hibernate4之一对一关系映射
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了hibernate4之一对一关系映射相关的知识,希望对你有一定的参考价值。
示例:一个用户(user) 住一个地址(address),一个地址有一个用户。
public class User{ private Integer id; private String name; private Address address; //getter and setter }
public class Address { private Integer id; private String addressName; private User user; //getter and setter }
用XML映射
<hibernate-mapping package="com.shen.hibernate4.entity"> <class name="User" table="tb_user"> <id name="id"> <generator class="identity" /> </id> <property name="name" /> <!--用外键来完成一对一关联,限制多方最多只能有一条记录参考到一方,这是多对一的一个特列。所以设置 many-to-one 的 unique 的属性为 true --> <many-to-one name="address" class="Address" column="address_id" unique="true"/> </class> </hibernate-mapping> <hibernate-mapping package="com.shen.hibernate4.entity"> <class name="Address" table="tb_address"> <id name="id"> <generator class="identity"/> </id> <property name="addressName" column="address_name"/> <!-- property-ref 属性 指定引用关联类的属性 --> <one-to-one name="user" class="User" property-ref="address" /> </class> </hibernate-mapping>
用@Annotation映射
@Entity @Table(name = "tb_user") public class User{ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String name; @OneToOne @JoinColumn(name = "address_id", unique = true) private Address address; //getter and setter }
@Entity @Table(name = "tb_address") public class Address { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String addressName; @OneToOne(mappedBy = "address") private User user; //getter and setter }
本文出自 “冰葫芦” 博客,请务必保留此出处http://shenlang7.blog.51cto.com/3102414/1742791
以上是关于hibernate4之一对一关系映射的主要内容,如果未能解决你的问题,请参考以下文章
mybatis xml数据层框架应用--Mybatis关系映射之一对一关系映射