[原创]java WEB学习笔记85:Hibernate学习之路-- -映射 一对一关系 ,基于主键方式实现

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[原创]java WEB学习笔记85:Hibernate学习之路-- -映射 一对一关系 ,基于主键方式实现相关的知识,希望对你有一定的参考价值。

本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用

内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系。

本人互联网技术爱好者,互联网技术发烧友

微博:伊直都在0221

QQ:951226918

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

1.基于主键映射的 1-1  

  1)基于主键的映射策略:指一端的主键生成器使用 foreign 策略,表明根据”对方”的主键来生成自己的主键,自己并不能独立生成主键. <param> 子元素指定使用当前持久化类的哪个属性作为 “对方

    

 1 <hibernate-mapping package="com.jason.hibernate.entities.primary.one2one">
 2 
 3     <class name="Department" table="DEPARTMENT">
 4     
 5         <id name="deptId" type="java.lang.Integer">
 6             <column name="DEPT_ID" />
 7             <generator class="foreign">
 8                 <param name="property">mgr</param>
 9             </generator>
10         </id>
11         
12         <property name="deptName" type="java.lang.String">
13             <column name="DEPT_NAME" />
14         </property>
15         
16         
17         <one-to-one name="mgr" class="Manager" constrained="true"></one-to-one>
18        
19         
20     </class>
21     
22 </hibernate-mapping>

 

 

 

  

  2)采用foreign主键生成器策略的一端增加 one-to-one 元素映射关联属性,其one-to-one属性还应增加 constrained=“true” 属性;另一端增加one-to-one元素映射关联属性。

  

 1 <hibernate-mapping package="com.jason.hibernate.entities.primary.one2one">
 2     <class name="Manager" table="MANAGER">
 3     
 4         <id name="mgrId" type="java.lang.Integer">
 5             <column name="MGR_ID" />
 6             <generator class="native" />
 7         </id>
 8         
 9         <property name="mgrName" type="java.lang.String">
10             <column name="MGR_NAME" />
11         </property>
12         
13         <one-to-one name="dept" class="Department"></one-to-one>
14        
15     </class>
16     
17 </hibernate-mapping>

 

 

  3)constrained(约束):指定为当前持久化类对应的数据库表的主键添加一个外键约束,引用被关联的对象(“对方”)所对应的数据库表主键

 

2.代码

技术分享

 

 

Department

 1 package com.jason.hibernate.entities.foreign.one2one;
 2 
 3 public class Department {
 4     private Integer deptId;
 5     private String deptName;
 6 
 7     private Manager mgr;
 8 
 9     public Integer getDeptId() {
10         return deptId;
11     }
12 
13     public void setDeptId(Integer deptId) {
14         this.deptId = deptId;
15     }
16 
17     public String getDeptName() {
18         return deptName;
19     }
20 
21     public void setDeptName(String deptName) {
22         this.deptName = deptName;
23     }
24 
25     public Manager getMgr() {
26         return mgr;
27     }
28 
29     public void setMgr(Manager mgr) {
30         this.mgr = mgr;
31     }
32 
33 }

 

 

Manager

 1 package com.jason.hibernate.entities.foreign.one2one;
 2 
 3 public class Manager {
 4 
 5     private Integer mgrId;
 6     private String mgrName;
 7     private Department dept;
 8 
 9     public Integer getMgrId() {
10         return mgrId;
11     }
12 
13     public void setMgrId(Integer mgrId) {
14         this.mgrId = mgrId;
15     }
16 
17     public String getMgrName() {
18         return mgrName;
19     }
20 
21     public void setMgrName(String mgrName) {
22         this.mgrName = mgrName;
23     }
24 
25     public Department getDept() {
26         return dept;
27     }
28 
29     public void setDept(Department dept) {
30         this.dept = dept;
31     }
32 
33 }

 

 

Department.hbm.xml

 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 <!-- Generated 2016-10-5 22:31:35 by Hibernate Tools 3.4.0.CR1 -->
 5 <hibernate-mapping package="com.jason.hibernate.entities.primary.one2one">
 6 
 7     <class name="Department" table="DEPARTMENT">
 8     
 9         <id name="deptId" type="java.lang.Integer">
10             <column name="DEPT_ID" />
11             <generator class="foreign">
12                 <param name="property">mgr</param>
13             </generator>
14         </id>
15         
16         <property name="deptName" type="java.lang.String">
17             <column name="DEPT_NAME" />
18         </property>
19         
20         
21         <one-to-one name="mgr" class="Manager" constrained="true"></one-to-one>
22        
23         
24     </class>
25     
26 </hibernate-mapping>

 

 

Manager.hbm.xml

 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 <!-- Generated 2016-10-5 22:31:35 by Hibernate Tools 3.4.0.CR1 -->
 5 <hibernate-mapping package="com.jason.hibernate.entities.primary.one2one">
 6     <class name="Manager" table="MANAGER">
 7     
 8         <id name="mgrId" type="java.lang.Integer">
 9             <column name="MGR_ID" />
10             <generator class="native" />
11         </id>
12         
13         <property name="mgrName" type="java.lang.String">
14             <column name="MGR_NAME" />
15         </property>
16         
17         <one-to-one name="dept" class="Department"></one-to-one>
18        
19     </class>
20     
21 </hibernate-mapping>

 

 

 

 

hibernate.cfg.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE hibernate-configuration PUBLIC
 3         "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
 4         "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
 5 <hibernate-configuration>
 6     <session-factory>
 7         <!-- hibernate 连接数据库的基本信息 -->
 8         <property name="connection.username">root</property>
 9         <property name="connection.password">zhangzhen</property>
10         <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
11         <property name="connection.url">jdbc:mysql:///hibernate</property>
12         
13         
14         <!-- 配置hibernate 的节本信息 -->
15         <!-- hibernate 所使用的数据库方言 -->
16         <!--<property name="dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>-->
17    <property name="dialect">org.hibernate.dialect.MySQLDialect</property> 
18         <!-- 执行操作时是否在控制台打印SQL  -->
19         <property name="show_sql">true</property>
20         
21         <!-- 是否都SQL 进行格式化 -->
22         <property name="format_sql">true</property>
23         
24         
25         <!-- 指定自动生成数据表的策略 -->
26         <property name="hbm2ddl.auto">update</property>
27         
28         <!-- 设置hibernate 的事务隔离级别 -->
29         <property name="connection.isolation">2</property>
30         
31         
32         <!-- 配置c3p0 -->
33         <property name="hibernate.c3p0.max_size">10</property>
34         <property name="hibernate.c3p0.min_size">5</property>
35         <property name="c3p0.acquire_increment">2</property>
36         <property name="c3p0.idle_test_period">2000</property>
37         <property name="c3p0.timeout">2000</property>
38         <property name="c3p0.max_statements">10</property>
39         
40         
41         <!-- 对于mysql 无效,对于oracle 有效 -->
42         <!-- 设定JDBC 的Statement 读取数据的时候每次从数据库中取出的记录的条数 -->
43         <property name="hibernate.jdbc.fetch_size">100</property>
44         
45         <!-- 设置数据库进行批量删除,批量更新和批量插入的时候的大小 -->
46         <property name="hibernate.jdbc.batch_size">30</property>
47         
48         <!-- 指定关联的 .hbm.xml 文件 -->
49         <!-- 
50             <mapping resource="hibernate/helloworld/News.hbm.xml"/>
51             <mapping resource="hibernate/helloworld/Worker.hbm.xml"/>
52         
53             <mapping resource="com/jason/hibernate/entities/n21/Customer.hbm.xml"/>
54             <mapping resource="com/jason/hibernate/entities/n21/Order.hbm.xml"/>
55         -->
56         
57          <mapping resource="com/jason/hibernate/entities/n21/both/Customer.hbm.xml"/>       
58          <mapping resource="com/jason/hibernate/entities/n21/both/Order.hbm.xml"/>       
59         
60         
61         <!-- 1-1 映射 -->
62         <!-- 基于外键实现 -->
63         <!-- <mapping resource="com/jason/hibernate/entities/foreign/one2one/Manager.hbm.xml"/>
64         <mapping resource="com/jason/hibernate/entities/foreign/one2one/Department.hbm.xml"/>
65          -->
66         <!-- 基于主键实现 -->
67         <mapping resource="com/jason/hibernate/entities/primary/one2one/Manager.hbm.xml"/>
68         <mapping resource="com/jason/hibernate/entities/primary/one2one/Department.hbm.xml"/>
69         
70         
71     </session-factory>
72     
73 </hibernate-configuration>

 

 

 

HibernateTest.java

  1 package com.jason.hibernate.entities.foreign.one2one;
  2 
  3 import hibernate.helloworld.News;
  4 
  5 import java.util.Date;
  6 
  7 import org.hibernate.Hibernate;
  8 import org.hibernate.Session;
  9 import org.hibernate.SessionFactory;
 10 import org.hibernate.Transaction;
 11 import org.hibernate.cfg.Configuration;
 12 import org.hibernate.service.ServiceRegistry;
 13 import org.hibernate.service.ServiceRegistryBuilder;
 14 import org.junit.After;
 15 import org.junit.Before;
 16 import org.junit.Test;
 17 
 18 public class HibernateTest {
 19 
 20     private SessionFactory sessionFactory;
 21     private Session session;
 22     private Transaction transaction;
 23     @Test
 24     public void test() {
 25 
 26         // 1. 创建一个SessionFatory 对象
 27         SessionFactory sessionFactory = null;
 28 
 29         // 1) 创建Configuration 对象:对应hibernate 的基本配置信息 和 对象关系映射信息
 30         Configuration configuration = new Configuration().configure();
 31 
 32         // 2) 创建一个ServiceRegistry 对象:hibernate 4.x 新天添加的对象。
 33         // hibernate 的任何配置 和 服务都需要在该对象中注册后才有效
 34         ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
 35                 .applySettings(configuration.getProperties())
 36                 .buildServiceRegistry();
 37 
 38         // sessionFactory = configuration.buildSessionFactory();
 39         sessionFactory = configuration.buildSessionFactory(serviceRegistry);
 40 
 41         // 2. 创建一个session 对象
 42         Session session = sessionFactory.openSession();
 43 
 44         // 3. 开启事物
 45         Transaction transaction = session.beginTransaction();
 46 
 47         // 4.执行保存操作
 48         News news = new News("java", "jason", new Date(
 49                 new java.util.Date().getTime()));
 50         session.save(news);
 51 
 52         // 5.提交事物
 53         transaction.commit();
 54         // 6.关闭session
 55         session.close();
 56         // 7.关闭SessionFactory 对象
 57         sessionFactory.close();
 58     }
 59 
 60     // 创建上述三个对象
 61     @Before
 62     public void init() {
 63         Configuration configuration = new Configuration().configure();
 64         ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
 65                 .applySettings(configuration.getProperties())
 66                 .buildServiceRegistry();
 67 
 68         sessionFactory = configuration.buildSessionFactory(serviceRegistry);
 69 
 70         session = sessionFactory.openSession();
 71 
 72         transaction = session.beginTransaction();
 73     }
 74 
 75     // 关闭上述三个对象
 76     @After
 77     public void destroy() {
 78         transaction.commit();
 79         session.close();
 80         sessionFactory.close();
 81     }
 82 
 83     
 84     @Test
 85     public void testSave(){
 86         
 87         Department department = new Department();
 88         department.setDeptName("DEPT-BB");
 89         
 90         Manager manager = new Manager();
 91         manager.setMgrName("MGR-BB");
 92         
 93         
 94         //设定关联关系
 95         department.setMgr(manager);
 96         manager.setDept(department);
 97         
 98         //保存
 99         //建议先保存没有外键列的那个对象,这样会减少update 语句
100         session.save(manager);
101         session.save(department);
102         
103         
104     }
105     
106     @Test
107     public void testGet(){
108         
109         //1.默认情况下对关联属性使用懒加载
110         Department dept = (Department) session.get(Department.class, 1);
111         System.out.println(dept.getDeptName());
112         
113         
114         //2.查询Manager 对象的连接条件应该是dept.manager_id = mgr.manager_id
115         //而不因该是  manager0_.MGR_ID=department1_.DEPT_ID 
116         Manager mgr = dept.getMgr();
117         System.out.println(mgr);
118     }
119     
120     
121     @Test
122     public void testGet2(){
123         
124         //在查询没有外键的实体对象,使用的是左外连接查询,一并查询出其关联的对象,并已经进行初始化
125         Manager manager = (Manager) session.get(Manager.class, 1);
126         System.out.println(manager);
127         
128         System.out.println(manager.getDept().getDeptName());
129         
130     }
131     
132     
133     
134     
135 }

 

以上是关于[原创]java WEB学习笔记85:Hibernate学习之路-- -映射 一对一关系 ,基于主键方式实现的主要内容,如果未能解决你的问题,请参考以下文章

[原创]java WEB学习笔记10:GenericServlet

[原创]java WEB学习笔记18:java EE 中的MVC 设计模式

[原创]java WEB学习笔记08:ServletResponse & HttpServletResponse

[原创]java WEB学习笔记20:案例完整实践(part 1)---MVC架构分析

[原创]java WEB学习笔记21:案例完整实践(part 2)---.DAO层设计

[原创]java WEB学习笔记13:JSP介绍(背景,特点,原理)