hibernate类之间的引用关系(一对一,一对多/多对一,多对多)

介绍:什么是关联(association)

理解:
1)关联指的是类之间的引用关系。如果类A与类B关联,
那么被引用的类B将被定义为类A的属性。例如:
public class A{
private B b = new B;
public A(){}
}
类型:
1)关联的分类:关联可以分为一对一、一对多/多对一、和多对多关联
关联是有方向的

1.一对多订单对多个订单项

解决方案二:spring中工具类 建议使用第二种
注2:集合属性只能用接口,不能用类
在这里插入图片描述

2.多对一订单项对单个订单

在这里插入图片描述
Person Idcard

#关键点都在数据库中的外键上面,请好好理解下面这二句SQL和一对多及多对一的关系

  1. 案例:如何建立订单和订单项的一对多双向关联
    2.1 先不建立订单和订单项的关联关系,定义实体及映射文件,单独执行保存操作
    在这里插入图片描述
    2.2 建立订单到订单项的一对多关联关系




    注1:hibernate3.0以后关联级别均为延时加载(代理对象)
    不使用立即加载的情况下如何访问关联级别的对象呢?
    解决方案一:编程控制,Hibernate.initialize(o.getOrderItems());

Order.hbm.xml源码:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
	<class name="com.zking.text.Entity.Order" table="t_order">
	
<!-- 不能使用普通的Property标签 -->
<!-- <property name="id" type="java.lang.Integer" column="id"></property> -->
<id name="orderId" type="java.lang.Integer" column="order_id"> 
	<generator class="native"></generator><!-- java自增长 -->
</id>
<property name="orderNo" type="java.lang.String">
	<column name="order_no"></column>
</property>
<set name="orderItemSet" inverse="true" cascade="save-update">
      <key column="oid"></key><!-- 连接外键oid -->
      <one-to-many class="com.zking.text.Entity.OrderItem"></one-to-many>
</set>
</class>
</hibernate-mapping>

在这里插入图片描述

             Set
       HashSet $Xxx

2.3 建立订单项到订单的多对一关联关系

  <!--1.注释 2.只读-->
  <property name="oid" type="java.lang.Integer" column="oid" insert="false" update="false">
  </property>

OrderItem.hbm.xml源码:

   <?xml version="1.0" encoding="UTF-8"?>
<hibernate-mapping>
	<class name="com.zking.text.Entity.OrderItem" table="t_order_item">
	
	<!-- 不能使用普通的Property标签 -->
	<!-- <property name="id" type="java.lang.Integer" column="id"></property> -->
	<id name="orderItemId" type="java.lang.Integer" column="order_item_id">
		<generator class="native"></generator><!-- java自增长 -->
	</id>
	<property name="productId" type="java.lang.Integer" column="product_id"></property>
	<property name="quantity" type="java.lang.Integer" column="quantity"></property>
	<property name="oid" type="java.lang.Integer" column="oid" 
	insert="false" update="false"></property><!-- 把oid设置为Java主键不能增加不能修改 -->
	<many-to-one name="order" class="com.zking.text.Entity.Order" column="oid" /><!-- 指向Order里面的oid -->
</class>
</hibernate-mapping>

在这里插入图片描述

2.4 注意:在Hibernate当中定义实体对象的集合属性时,只能使用接口而不能使用类,映射文件一定要配置到核心文件中
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>
		<property name="connection.username">root</property>
	<property name="connection.password">123</property>
	<!-- xml的&要写成&amp -->
	<property name="connection.url">jdbc:mysql://localhost:3306/hjj?useUnicode=true&amp;characterEncoding=UTF-8&amp;useSSL=false</property>
	<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
	<!-- 方言:跨数据库的无缝移植 -->
	<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
	
	<!-- 调试相关 -->
	<property name="show_sql">true</property><!-- 测试sql语句 -->
	<property name="format_sql">true</property><!-- 格式化 -->
	
		<!-- 添加实体映射文件 -->
	<mapping resource="mapping/Order.hbm.xml"/>
	<mapping resource="mapping/OrderItem.hbm.xml"/>
	</session-factory>

</hibernate-configuration>

#insert属性设置中主控方概念理解:

3. 以客户和订单的一对多双向关联为例,讲解Set元素中的cascade|inverse|outter-join|lazy属性作用

3.1 lazy:默认值为true,true延迟加载,false立即加载(一般设置为true,不使用立即加载,因为影响查询性能)

3.2 outter-join:默认值为false,true使用左外联接查询关联的(但一般不用,因为当我们把该属性设置为true时,所有的查询语句都会默认左外联,那样性能不高)
3.3 inverse:默认值为false,true表示将对方设置为主控方(一对多双向关联中一般将多方设置为主控方,这样可以减少SQL语句的数量,减少多余的操作)
3.4 cascade:用来控制如何操作关联的持久化对象的
3.4.1 none:保存,更新或删除当前对象时,忽略其它关联的对象
3.4.2 save-update:保存、更新时级联保存所有的临时对象,并且级联更新关联的游离对象
3.4.3 delete:通过session的delete方法删除当前对象,级联删除关联的对象
3.4.4 all:等于save-update操作+delete操作
在这里插入图片描述

小结:
多方的CRUD与没有建立关联关系之前的操作一致
一方的CRUD与没有建立关联关系之前的操作有变化
D:删除一方之前先删除多方
C:级联操作
R:将多方设为主控制

  1. 案例:菜单对象的一对多双向自关联




  2. 如何将多方映射成一个有序的集合

测试工具类:

SessionFactoryUtil:

package com.zking.text.Util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class SessionFactoryUtil {
	//静态属性
	private static SessionFactory sessionFactory;
	//ThreadLocal对象用来获得会话
	private static ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();


static {//静态块,也只执行一次
	Configuration configuration = new Configuration();
	configuration.configure("hibernate.cfg.xml");
	sessionFactory=configuration.buildSessionFactory();
}
/**
 * 打开会话,保存在同一请求中只打开一次
 * @return
 */
public static Session openSession() {
	Session session = threadLocal.get();
	if(null == session) {
		session=sessionFactory.openSession();
		threadLocal.set(session);
	}
	return session;
}
/**
 * 关闭会话
 * @return
 */
public static void closeSession() {
	Session session = threadLocal.get();
	if(null != session) {
		if(session.isOpen()) {
			session.close();
		}
		//两种状态清空Session
		//threadLocal.set(null);
		threadLocal.remove();
	}
}

public static void main(String[] args) {
	Session session =  openSession();
	//判断Session是否连接成功
	System.out.println(session.isConnected());
	closeSession();
	System.out.println("ok");
}

}

在这里插入图片描述

编写Dao来进行(增删改查(单个查询))

XxxxDao源码:

package com.zking.text.Dao;

import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.zking.text.Entity.Order;
import com.zking.text.Entity.OrderItem;
import com.zking.text.Util.SessionFactoryUtil;

public class OrderDao {

/**
 * 保存订单的同时级联保存订单项
 * 
 * @param order
 */
public void add(Order order) {// 将学完spring之后就没有
	Session session = null;
	Transaction transaction = null;
	try {
		session = SessionFactoryUtil.openSession();
		transaction = session.beginTransaction();// 开启事务

		// CRUD
		session.save(order);// 只要一行代码

		transaction.commit();// 提交事务
	} catch (Exception e) {
		if (null != transaction) {
			transaction.rollback();// 回滚事务
		}
		throw new RuntimeException(e);
	} finally {
		SessionFactoryUtil.closeSession();
	}
}

/**
 * 有细节要处理
 * 
 * @param order
 * @return
 */
public Order load(Order order) {
	Order o = null;
	Session session = null;
	Transaction transaction = null;
	try {
		session = SessionFactoryUtil.openSession();
		transaction = session.beginTransaction();// 开启事务

		// CRUD
		o = session.get(Order.class, order.getOrderId());
		if (new Integer(1).equals(order.getInitOrderItemSet())) {
			Hibernate.initialize(o.getOrderItemSet());// 强制初始化Set集合
		}

		transaction.commit();// 提交事务

		return o;
	} catch (Exception e) {
		if (null != transaction) {
			transaction.rollback();// 回滚事务
		}
		throw new RuntimeException(e);
	} finally {
		SessionFactoryUtil.closeSession();
	}
}

/**
 * 有细节要处理 直接删除订单有时会失败,因为没有处理订单项
 * 
 * @param order
 */
public void del(Order order) {// 将学完spring之后就没有
	Session session = null;
	Transaction transaction = null;
	try {
		session = SessionFactoryUtil.openSession();
		transaction = session.beginTransaction();// 开启事务

		// CRUD
		Order o = session.get(Order.class, order.getOrderId());
		if (null != o) {// 先删除订单项再删除订单
			for (OrderItem item : o.getOrderItemSet()) {
				session.delete(item);
			}
			session.delete(o);
		}

		transaction.commit();// 提交事务
	} catch (Exception e) {
		if (null != transaction) {
			transaction.rollback();// 回滚事务
		}
		throw new RuntimeException(e);
	} finally {
		SessionFactoryUtil.closeSession();
	}
}

public void edit(Order order) {// 将学完spring之后就没有
	Session session = null;
	Transaction transaction = null;
	try {
		session = SessionFactoryUtil.openSession();
		transaction = session.beginTransaction();// 开启事务

		Order o = session.get(Order.class, order.getOrderId());
		if (null != o) {
			o.setOrderNo(order.getOrderNo());
		}

		transaction.commit();// 提交事务
	} catch (Exception e) {
		if (null != transaction) {
			transaction.rollback();// 回滚事务
		}
		throw new RuntimeException(e);
	} finally {
		SessionFactoryUtil.closeSession();
	}
}
}
使用junit测试DaoTest

OrderDaoTest源码:

package com.zking.text.Dao;

import static org.junit.Assert.*;

import org.junit.Before;
import org.junit.Test;

import com.zking.text.Entity.Order;
import com.zking.text.Entity.OrderItem;

public class OrderDaoTest {

private OrderDao orderdao = new OrderDao();

private Order order;

@Before
public void before() {
	order = new Order();
}

@Test
public void testAdd() {//保存订单同时并把订单项保存了
	order =new Order();
	order.setOrderNo("8350");
	OrderItem orderitem = new OrderItem();
	orderitem.setOrderItemId(null);
	orderitem.setProductId(1);
	orderitem.setQuantity(2);
	//orderitem.setOid(oid);不需要编写insert="false" update="false";
	//给订单项创建对象的关联关系
	order.getOrderItemSet().add(orderitem);//建立订单对订单项一对多的关系
	orderitem.setOrder(order);//建立订单项对订单多对一的关系
	orderdao.add(order);//再也不需要循环取保存订单项
}

@Test
public void load() {
	order.setOrderId(2);
	order.setInitOrderItemSet(1);

	Order o = orderdao.load(order);
	// System.out.println(o.getOrderId());
	System.out.println(o.getOrderNo());

	// System.out.println("xxxxxxxxxxxxxxxxxxxx");
	System.out.println("size=" + o.getOrderItemSet().size());
	// System.out.println("ok");
}

@Test
public void edit() {
	order.setOrderId(5);
	order.setOrderNo("18350");
	
	orderdao.edit(order);

	System.out.println("ok");
}

@Test
public void del() {
	order.setOrderId(2);

	orderdao.del(order);
	System.out.println("ok");
}


}

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值