标签:一对一关系映射
示例:一个用户(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
标签:一对一关系映射
原文地址:http://shenlang7.blog.51cto.com/3102414/1742791