示例:一个用户(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 }
时间: 2024-10-22 08:11:52