其他分享
首页 > 其他分享> > Hibernate关联关系 之 一对多

Hibernate关联关系 之 一对多

作者:互联网

Hibernate关联关系 之 一对多

Hibernate关联关系

什么是关联? (association)
关联指的是类之间的引用关系。
如果类A与类B关联,那么被引用的类B将被定义为类A的属性。
例如:

 class B{
	private String name;
  }
  
  public class A{
    private B b = new B;
    public A(){}
  }

hibernate:orm框架、以面向对象的思想操作数据库
实体类 ------> 表
属性 ---------> 字段

关联的分类 :
关联可以分为 一对一一对多/多对一多对多 关联
关联是有方向的

Hibernate 一对多关联

如何建立客户和订单一对多双向关联?

注意 :
在Hibernate当中定义实体对象的集合属性时,只能使用接口而不能使用类


案例操作

数据库

t_hibernate_order:
在这里插入图片描述
t_hibernate_order_item:
在这里插入图片描述


实体类 entity

重要代码:

Order:

	private Integer orderId;
	private String orderNo;
	private List<OrderItem> orderItems = new ArrayList<>();//一个订单对应多个订单项
	private Integer initChildren = 0;//0--懒加载  1--false
	

OrderItem:

	private Integer orderItemId;
	private Integer productId;
	private Integer quantity;
	private Integer oid;
	private Order order = new Order();//一个订单项对应一个订单
	

xml 配置

Order.hbm.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
	
	<class name="com.dj.three.entity.Order" table="t_hibernate_order">
		<id name="orderId" type="java.lang.Integer" column="order_id">
			<generator class="increment" />
		</id>
		<property name="orderNo" type="java.lang.String" column="order_no"></property>
		
		<!-- 
			bag标签:
				lazy:是否懒加载,默认是懒加载 true     懒汉模式
				name:类的关联属性名
				cascade:级联关系  级联新增与修改
				inverse:关联关系交给对方控制,默认是true,当前类不维护关联关系
				
				子标签:
					key:
						column:主表的主键,从表的外键
					
					one-to-many:
						class:外键对应的实体类	
		 -->
		<bag lazy="true" name="orderItems" cascade="save-update" inverse="true" >
			<!-- 从表的外键 -->
			<key column="oid"></key>
			<!-- 从表的外键对应的实体类 -->
			<one-to-many class="com.dj.three.entity.OrderItem" />
		</bag>
	</class>

</hibernate-mapping>

OrderItem.hbm.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
	<class name="com.dj.three.entity.OrderItem" table="t_hibernate_order_item">
		<id name="orderItemId" type="java.lang.Integer" column="order_item_id">
			<generator class="increment" />
		</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>
		
		<many-to-one name="order" class="com.dj.three.entity.Order" column="oid"></many-to-one>
	</class>
</hibernate-mapping>

DemoDao

package com.dj.three.dao;

import java.util.List;

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

import com.dj.three.entity.Order;
import com.dj.three.entity.OrderItem;
import com.dj.two.util.SessionFactoryUtils;

public class DemoDao {
	
	/**
	 * 为了测试关系型映射文件配置准确
	 * 	讲解insert=false,update=false的用途
	 * 
	 * 增加订单
	 * 
	 * @param order
	 * @return
	 */
	public Integer addOrder(Order order) {
		Session session = SessionFactoryUtils.openSession();
		Transaction transaction = session.beginTransaction();
		Integer oid = (Integer)session.save(order);
		transaction.commit();
		session.close();
		return oid;
	}
	
	/**
	 * 增加订单项
	 * @param orderItem
	 * @return
	 */
	public Integer addOrderItem(OrderItem orderItem) {
		Session session = SessionFactoryUtils.openSession();
		Transaction transaction = session.beginTransaction();
		Integer otid = (Integer)session.save(orderItem);
		transaction.commit();
		session.close();
		return otid;
	}
	
	
	
	/**
	 * 为了讲解懒加载的问题(hibernate3.0后所有查询方式默认采用的是懒加载方式)
	 * 	1、查单个时存在问题,代理对象已经关闭
	 * 	2、查多个存在问题,有性能的问题
	 * @param order
	 * @return
	 */
	public Order getOrder(Order order) {
		Session session = SessionFactoryUtils.openSession();
		Transaction transaction = session.beginTransaction();
		Order o = session.get(Order.class, order.getOrderId());
		if(o != null && new Integer(1).equals(order.getInitChildren())) {
			//强制加载关联对象
			Hibernate.initialize(o.getOrderItems());
//			System.out.println(o.getOrderItems());
		}
		transaction.commit();
		session.close();
		return o;
	}
	
	public List<Order> getOrderList() {
		Session session = SessionFactoryUtils.openSession();
		Transaction transaction = session.beginTransaction();
		List<Order> list = session.createQuery("from Order").list();
		transaction.commit();
		session.close();
		return list;
	}
	
	/**
	 * z主表的数据不能随便删除,得先删除从表中对应信息,才能删除主表的信息。
	 * @param order
	 */
	public void delOrder(Order order) {
		Session session = SessionFactoryUtils.openSession();
		Transaction transaction = session.beginTransaction();
		Order order2 = session.get(Order.class, order.getOrderId());
		for (OrderItem oi : order2.getOrderItems()) {
			session.delete(oi);
		}
		session.delete(order2);
//		session.delete(order);
		transaction.commit();
		session.close();
	}
}

DemoDaoTest

package com.dj.three.dao;

import java.util.List;

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

import com.dj.three.entity.Order;
import com.dj.three.entity.OrderItem;

/**
 * @Before 每测试一个 @test 标记的测试方法,都会在调用之前执行一次
 * @After 每测试一个 @test 标记的测试方法,都会在调用之后执行一次
 * @author 86182
 *
 */
public class DemoDaoTest {
	private DemoDao demoDao = new DemoDao();

	/*@Before
	public void setUp() throws Exception {
		System.out.println("加载资源");
	}

	@After
	public void tearDown() throws Exception {
		System.out.println("释放资源");
	}*/

	@Test
	public void testAddOrder() {
		//实例化一个订单
		Order order = new Order();
		order.setOrderNo("p20");
		OrderItem orderItem = null;
		for(int i = 0; i < 6; i++) {
			//实例化一个订单项
			orderItem = new OrderItem();
			orderItem.setProductId(10+i);
			orderItem.setQuantity(20+i);
			//维护关系
			orderItem.setOrder(order);
			order.getOrderItems().add(orderItem);
		}
		//增加订单
		demoDao.addOrder(order);
	}

	@Test
	public void testAddOrderItem() {
		/*//实例化一个订单项
		OrderItem orderItem = new OrderItem();
		orderItem.setProductId(12);
		orderItem.setQuantity(22);
		//实例化一个订单
		Order order = new Order();
		order.setOrderId(8);
		order.getOrderItems().add(orderItem);
		orderItem.setOrder(order);
		//增加订单项
		demoDao.addOrderItem(orderItem); */	
		
		
		//实例化一个订单项
		OrderItem orderItem = null;
		for(int i = 0; i < 6; i++) {
			orderItem = new OrderItem();
			orderItem.setProductId(10+i);
			orderItem.setQuantity(20+i);
			//维护关系
			//实例化一个订单
			Order order = new Order();
			order.setOrderId(7);
			order.getOrderItems().add(orderItem);
			orderItem.setOrder(order);
			//增加订单项
			demoDao.addOrderItem(orderItem);
		}
		
	}

	@Test
	public void testGetOrder() {
		/**
		 * 当lazy=false时,
		 * hibernate执行完两次操作后,session才会关闭(数据库操作了两次)
		 * 
		 * 当lazy=true时,
		 * hibernate执行完一次操作后,session就会关闭
		 * 
		 * 综上所述,lazy=false更好,那为什么hibernate默认lazy为ture呢?
		 * hibernate3.0出现lazy属性,是出于性能的考虑,并默认lazy=true,
		 * 也就是说,不加载关联属性。
		 */
		//实例化一个订单
		Order order = new Order();
		order.setOrderId(8);
		//order.setInitChildren(1);
		Order o = this.demoDao.getOrder(order);
		List<OrderItem> orderItems = o.getOrderItems();
		for (OrderItem orderItem : orderItems) {
			System.out.println(orderItem);
		}
		System.out.println(o);
		
	}

	@Test
	public void testGetOrderList() {
		List<Order> orderList = this.demoDao.getOrderList();
		for (Order order : orderList) {
			for (OrderItem orderItem : order.getOrderItems()) {
				System.out.println(orderItem);
			}
			System.out.println(order);
		}
		
	}

	@Test
	public void testDelOrder() {
		//实例化一个订单
		Order order = new Order();
		order.setOrderId(7);
		this.demoDao.delOrder(order);
		
	}

}


Hibernate框架一对多的执行原理

标签:Hibernate,orderItem,关联,order,public,session,new,一对,Order
来源: https://blog.csdn.net/qq_44641053/article/details/96007858