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

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

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

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

微博:伊直都在0221

QQ:951226918

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

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

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

    

 <hibernate-mapping package="com.jason.hibernate.entities.primary.one2one">

     <class name="Department" table="DEPARTMENT">

         <id name="deptId" type="java.lang.Integer">
<column name="DEPT_ID" />
<generator class="foreign">
8 <param name="property">mgr</param>
9 </generator>

</id> <property name="deptName" type="java.lang.String">
<column name="DEPT_NAME" />
</property> <one-to-one name="mgr" class="Manager" constrained="true"></one-to-one> </class> </hibernate-mapping>

  

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

  

 <hibernate-mapping package="com.jason.hibernate.entities.primary.one2one">
<class name="Manager" table="MANAGER"> <id name="mgrId" type="java.lang.Integer">
<column name="MGR_ID" />
<generator class="native" />
</id> <property name="mgrName" type="java.lang.String">
<column name="MGR_NAME" />
</property> <one-to-one name="dept" class="Department"></one-to-one> </class> </hibernate-mapping>

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

2.代码

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

Department

 package com.jason.hibernate.entities.foreign.one2one;

 public class Department {
private Integer deptId;
private String deptName; private Manager mgr; public Integer getDeptId() {
return deptId;
} public void setDeptId(Integer deptId) {
this.deptId = deptId;
} public String getDeptName() {
return deptName;
} public void setDeptName(String deptName) {
this.deptName = deptName;
} public Manager getMgr() {
return mgr;
} public void setMgr(Manager mgr) {
this.mgr = mgr;
} }

Manager

 package com.jason.hibernate.entities.foreign.one2one;

 public class Manager {

     private Integer mgrId;
private String mgrName;
private Department dept; public Integer getMgrId() {
return mgrId;
} public void setMgrId(Integer mgrId) {
this.mgrId = mgrId;
} public String getMgrName() {
return mgrName;
} public void setMgrName(String mgrName) {
this.mgrName = mgrName;
} public Department getDept() {
return dept;
} public void setDept(Department dept) {
this.dept = dept;
} }

Department.hbm.xml

 <?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2016-10-5 22:31:35 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping package="com.jason.hibernate.entities.primary.one2one"> <class name="Department" table="DEPARTMENT"> <id name="deptId" type="java.lang.Integer">
<column name="DEPT_ID" />
<generator class="foreign">
<param name="property">mgr</param>
</generator>
</id> <property name="deptName" type="java.lang.String">
<column name="DEPT_NAME" />
</property> <one-to-one name="mgr" class="Manager" constrained="true"></one-to-one> </class> </hibernate-mapping>

Manager.hbm.xml

 <?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2016-10-5 22:31:35 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping package="com.jason.hibernate.entities.primary.one2one">
<class name="Manager" table="MANAGER"> <id name="mgrId" type="java.lang.Integer">
<column name="MGR_ID" />
<generator class="native" />
</id> <property name="mgrName" type="java.lang.String">
<column name="MGR_NAME" />
</property> <one-to-one name="dept" class="Department"></one-to-one> </class> </hibernate-mapping>

hibernate.cfg.xml

 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- hibernate 连接数据库的基本信息 -->
<property name="connection.username">root</property>
<property name="connection.password">zhangzhen</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql:///hibernate</property> <!-- 配置hibernate 的节本信息 -->
<!-- hibernate 所使用的数据库方言 -->
<!--<property name="dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>-->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 执行操作时是否在控制台打印SQL -->
<property name="show_sql">true</property> <!-- 是否都SQL 进行格式化 -->
<property name="format_sql">true</property> <!-- 指定自动生成数据表的策略 -->
<property name="hbm2ddl.auto">update</property> <!-- 设置hibernate 的事务隔离级别 -->
<property name="connection.isolation">2</property> <!-- 配置c3p0 -->
<property name="hibernate.c3p0.max_size">10</property>
<property name="hibernate.c3p0.min_size">5</property>
<property name="c3p0.acquire_increment">2</property>
<property name="c3p0.idle_test_period">2000</property>
<property name="c3p0.timeout">2000</property>
<property name="c3p0.max_statements">10</property> <!-- 对于mysql 无效,对于oracle 有效 -->
<!-- 设定JDBC 的Statement 读取数据的时候每次从数据库中取出的记录的条数 -->
<property name="hibernate.jdbc.fetch_size">100</property> <!-- 设置数据库进行批量删除,批量更新和批量插入的时候的大小 -->
<property name="hibernate.jdbc.batch_size">30</property> <!-- 指定关联的 .hbm.xml 文件 -->
<!--
<mapping resource="hibernate/helloworld/News.hbm.xml"/>
<mapping resource="hibernate/helloworld/Worker.hbm.xml"/> <mapping resource="com/jason/hibernate/entities/n21/Customer.hbm.xml"/>
<mapping resource="com/jason/hibernate/entities/n21/Order.hbm.xml"/>
--> <mapping resource="com/jason/hibernate/entities/n21/both/Customer.hbm.xml"/>
<mapping resource="com/jason/hibernate/entities/n21/both/Order.hbm.xml"/> <!-- 1-1 映射 -->
<!-- 基于外键实现 -->
<!-- <mapping resource="com/jason/hibernate/entities/foreign/one2one/Manager.hbm.xml"/>
<mapping resource="com/jason/hibernate/entities/foreign/one2one/Department.hbm.xml"/>
-->
<!-- 基于主键实现 -->
<mapping resource="com/jason/hibernate/entities/primary/one2one/Manager.hbm.xml"/>
<mapping resource="com/jason/hibernate/entities/primary/one2one/Department.hbm.xml"/> </session-factory> </hibernate-configuration>

HibernateTest.java

 package com.jason.hibernate.entities.foreign.one2one;

 import hibernate.helloworld.News;

 import java.util.Date;

 import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test; public class HibernateTest { private SessionFactory sessionFactory;
private Session session;
private Transaction transaction;
@Test
public void test() { // 1. 创建一个SessionFatory 对象
SessionFactory sessionFactory = null; // 1) 创建Configuration 对象:对应hibernate 的基本配置信息 和 对象关系映射信息
Configuration configuration = new Configuration().configure(); // 2) 创建一个ServiceRegistry 对象:hibernate 4.x 新天添加的对象。
// hibernate 的任何配置 和 服务都需要在该对象中注册后才有效
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
.applySettings(configuration.getProperties())
.buildServiceRegistry(); // sessionFactory = configuration.buildSessionFactory();
sessionFactory = configuration.buildSessionFactory(serviceRegistry); // 2. 创建一个session 对象
Session session = sessionFactory.openSession(); // 3. 开启事物
Transaction transaction = session.beginTransaction(); // 4.执行保存操作
News news = new News("java", "jason", new Date(
new java.util.Date().getTime()));
session.save(news); // 5.提交事物
transaction.commit();
// 6.关闭session
session.close();
// 7.关闭SessionFactory 对象
sessionFactory.close();
} // 创建上述三个对象
@Before
public void init() {
Configuration configuration = new Configuration().configure();
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
.applySettings(configuration.getProperties())
.buildServiceRegistry(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); session = sessionFactory.openSession(); transaction = session.beginTransaction();
} // 关闭上述三个对象
@After
public void destroy() {
transaction.commit();
session.close();
sessionFactory.close();
} @Test
public void testSave(){ Department department = new Department();
department.setDeptName("DEPT-BB"); Manager manager = new Manager();
manager.setMgrName("MGR-BB"); //设定关联关系
department.setMgr(manager);
manager.setDept(department); //保存
//建议先保存没有外键列的那个对象,这样会减少update 语句
session.save(manager);
session.save(department); } @Test
public void testGet(){ //1.默认情况下对关联属性使用懒加载
Department dept = (Department) session.get(Department.class, 1);
System.out.println(dept.getDeptName()); //2.查询Manager 对象的连接条件应该是dept.manager_id = mgr.manager_id
//而不因该是 manager0_.MGR_ID=department1_.DEPT_ID
Manager mgr = dept.getMgr();
System.out.println(mgr);
} @Test
public void testGet2(){ //在查询没有外键的实体对象,使用的是左外连接查询,一并查询出其关联的对象,并已经进行初始化
Manager manager = (Manager) session.get(Manager.class, 1);
System.out.println(manager); System.out.println(manager.getDept().getDeptName()); } }
上一篇:Java中的接口与抽象类


下一篇:Jquery的Ready方法加载为什么两次?