一对一和多对一在配置上基本一致,只是需要在配置关联的一方添加unique="true"(基于XML配置而言),以人和身份证为例。
Idcard
1 package domain;
2
3 public class Idcard {
4
5 private int id;
6 private String num;
7 private Person person;
8 //get/set和构造省略,但实际不可省略
9
10 }
11
1 <?xml version="1.0"?>
2 <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
3 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
4
5 <hibernate-mapping>
6 <class name="domain.Idcard" table="IDCARD">
7 <id name="id" type="int">
8 <column name="ID" />
9 <generator class="native" />
10 </id>
11 <property name="num" type="java.lang.String">
12 <column name="NUM" />
13 </property>
14 <!-- 注意:unique配置只有在hibernate生成生成DDL的时候才会启用,若已存在数据表,则不会检查唯一性约束 -->
15 <!-- 配置unique="true",指明该多对一多的一方只有一个 -->
16 <many-to-one name="person" column="pid" class="domain.Person" unique="true" />
17 </class>
18 </hibernate-mapping>
19
1 package domain;
2
3 public class Person {
4
5 private int id;
6 private String name;
7 //get/set和构造省略,但实际不可省略
8
9 }
10
1 <?xml version="1.0"?>
2 <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
3 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
4
5 <hibernate-mapping>
6 <class name="domain.Person" table="PERSON">
7 <id name="id" type="int">
8 <column name="ID" />
9 <generator class="native" />
10 </id>
11 <property name="name" type="java.lang.String">
12 <column name="NAME" />
13 </property>
14 </class>
15
16 </hibernate-mapping>
17
书写测试类
1 package demo;
2
3 import org.hibernate.Session;
4 import org.junit.Test;
5
6 import domain.Idcard;
7 import domain.Person;
8 import util.HibernateUtil;
9
10 public class App
11 {
12
13 /**
14 * 一对一单向关联
15 */
16 @Test
17 public void addTest01() {
18 Session session = null;
19 try {
20 session = HibernateUtil.openSession();
21 session.beginTransaction();
22
23 Person person = new Person();
24 person.setName("Nick");
25 session.save(person);
26
27 Idcard idcard = new Idcard();
28 idcard.setNum("#2");
29 idcard.setPerson(person);
30 session.save(idcard);
31
32 session.getTransaction().commit();
33
34 } catch (Exception e) {
35 if (session != null) {
36 session.getTransaction().rollback();
37 }
38 } finally{
39 if (session != null) {
40 session.close();
41 }
42 }
43 }
44
45 /**
46 * 一对一单向关联,idcard一方维护一对一的关系,所以一个人不能有两个idcard
47 * 此处有异常
48 */
49 @Test
50 public void addTest02() {
51 Session session = null;
52 try {
53 session = HibernateUtil.openSession();
54 session.beginTransaction();
55
56 Person person = (Person) session.load(Person.class, 1);
57
58 Idcard idcard = new Idcard();
59 idcard.setNum("#2");
60 idcard.setPerson(person);
61 session.save(idcard);
62
63 session.getTransaction().commit();
64
65 } catch (Exception e) {
66 e.printStackTrace();
67 if (session != null) {
68 session.getTransaction().rollback();
69 }
70 } finally{
71 if (session != null) {
72 session.close();
73 }
74 }
75 }
76 }
77