hibernate关联(一对多)

1. 什么是关联(association)

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

t_hibernate_order(订单表) t_hibernate_order_item(订单项表)
一个订单对应多个订单项

Order (因为 Order 与 OrderItem关联, 订单项OrderItem被引用,所以被定义为Order的属性 private List orderItems=new ArrayList();)

package com.wr.three.entity;

import java.util.ArrayList;
import java.util.List;

public class Order {
	private Integer order_id;
	private String order_no;
	private List<OrderItem> orderItems=new ArrayList<OrderItem>();
	public Integer getOrder_id() {
		return order_id;
	}
	public void setOrder_id(Integer order_id) {
		this.order_id = order_id;
	}
	public String getOrder_no() {
		return order_no;
	}
	public void setOrder_no(String order_no) {
		this.order_no = order_no;
	}
	public List<OrderItem> getOrderItems() {
		return orderItems;
	}
	public void setOrderItems(List<OrderItem> orderItems) {
		this.orderItems = orderItems;
	}
	public Order(Integer order_id, String order_no, List<OrderItem> orderItems) {
		super();
		this.order_id = order_id;
		this.order_no = order_no;
		this.orderItems = orderItems;
	}
	public Order() {
		super();
	}
	
	
	
}

Order实体类的映射文件
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.wr.three.entity.Order" table="t_hibernate_order">
		<id name="order_id" type="java.lang.Integer" column="order_id">
			<generator class="increment" />
		</id>
		<property name="order_no" type="java.lang.String" column="order_no">
		</property>
		
		<!-- 
	bag标签:
		name:当前要映射的类的关联属性
		cascade:维护关联关系
		inverse:决定由谁来维护关联关系
	key标签
	 	column:表的外键对应的列段
	one-to-many标签:
		class:关联属性对应的类的全路径名
 -->
		<bag name="orderItems"  cascade="save-update" inverse="true">
		
			<key column="oid"></key>
			<one-to-many class="com.wr.three.entity.OrderItem"/>
		</bag>
		
		
	</class>

</hibernate-mapping>

OrderItem
( Order 与 OrderItem关联,订单Order被引用,所以被定义为OrderItem的属性
private Order order;

package com.wr.three.entity;

public class OrderItem {
	private Integer order_item_id;
	private Integer product_id;
	private Integer quantity;
	private Integer oid;
	private Order order;
	public Integer getOrder_item_id() {
		return order_item_id;
	}
	public void setOrder_item_id(Integer order_item_id) {
		this.order_item_id = order_item_id;
	}
	
	public Integer getProduct_id() {
		return product_id;
	}
	public void setProduct_id(Integer product_id) {
		this.product_id = product_id;
	}
	public Integer getQuantity() {
		return quantity;
	}
	public void setQuantity(Integer quantity) {
		this.quantity = quantity;
	}
	public Integer getOid() {
		return oid;
	}
	public void setOid(Integer oid) {
		this.oid = oid;
	}
	public Order getOrder() {
		return order;
	}
	public void setOrder(Order order) {
		this.order = order;
	}
	
	public OrderItem(Integer order_item_id, Integer product_id, Integer quantity, Integer oid, Order order) {
		super();
		this.order_item_id = order_item_id;
		this.product_id = product_id;
		this.quantity = quantity;
		this.oid = oid;
		this.order = order;
	}
	public OrderItem() {
		super();
	}



}

OrderItem实体类的映射文件 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.wr.three.entity.OrderItem"
		table="t_hibernate_order_item">
		<id name="order_item_id" type="java.lang.Integer"
			column="order_item_id">
			<generator class="increment" />
		</id>
		<property name="product_id" 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:当前所要映射的类(OrderItem)的关联属性(order) 
			class:关联属性的类别(全路径名) column:这里填外键 -->
		<many-to-one name="order"
			class="com.wr.three.entity.Order" column="oid"></many-to-one>

	</class>
</hibernate-mapping>

在hibernate.cfg.xml中配置一下那两个映射实体类

		<mapping resource="com/wr/three/entity/Order.hbm.xml" />
		<mapping resource="com/wr/three/entity/OrderItem.hbm.xml" />

下面是一些例子
DemoDao(里面是一些订单和订单项的一些添加,查看,删除的方法)

package com.wr.three.dao;

import java.util.List;

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

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

public class DemoDao {

	public Integer addOrder(Order order) {
		// 通过sessionfactory对象去获取session会话 		
		Session session = SessionFactoryUtils.openSession();
//		session开启事务
		Transaction transaction = session.beginTransaction();
//		操作数据库  
		Integer oid = (Integer) session.save(order);
//		提交事务
		transaction.commit();
//		释放资源
		session.close();
		return oid;
		
		
	}
	
	
	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.getList()) {
			session.delete(oi);
		}
		session.delete(order2);
//		session.delete(order);
		transaction.commit();
		session.close();
	}
	
	
	
}

创建一个DemoDaoTest类来测试这些方法

/**
* 两个都可以同时添加
* 添加订单的时候,也把订单项添加进来
* 而且只调用了一个dao方法
*/

	public void testAddOrder() {
		Order order=new Order();
		order.setOrder_no("T235购物");
		for (int i = 0; i < 6; i++) {
			OrderItem orderItem=new OrderItem();
			orderItem.setProduct_id(20+i);
			orderItem.setQuantity(40+i);
			order.getOrderItems().add(orderItem);
			orderItem.setOrder(order);
		}
		demoDao.addOrder(order);
	}

/**
*添加订单项
*/

@Test
	public void testAddOrderItem() {
		OrderItem orderItem=new OrderItem();
		orderItem.setProduct_id(666);
		orderItem.setQuantity(666);
		Order order=new Order();
		order.setOrder_id(11);
		orderItem.setOrder(order);
		demoDao.addOrderItem(orderItem);
	}

获取订单的方法

public void testGetOrder() {
		Order order=new Order();
		order.setOrder_id(10);
	Order  o=demoDao.getOrder(order);
	System.out.println(o.getOrder_no());
	System.out.println(o.getOrderItems());
	}

System.out.println(o.getOrderItems());就这样输不出来,需要去Order.hbm.xml的bag标签中配置一个 lazy=“false”(懒加载)。但这是一般人的做法,并不推从这种做法(执行的sql语句多,)


一个新的懒加载的方法: 给order实体来添加一个字段 private Integer initChildren=0;
//0代表默认懒加载,1代表强制加载
在DemoDao中的getOrder()方法添加一段代码 ,强制加载关联关系

	public Order getOrder(Order order) {
		Session session = SessionFactoryUtils.openSession();
		Transaction transaction = session.beginTransaction();
		Order o = session.get(Order.class, order.getOrder_id());
		//强制加载关联关系
		if(o != null && new Integer(1).equals (order.getInitChildren())) {
			Hibernate.initialize(o.getOrderItems());
//			System.out.println(o.getOrderItems());
		}
		transaction.commit();
		session.close();
		return o;
	}

DemoDaoTest

package com.wr.three.dao;

import static org.junit.Assert.*;

import java.util.List;

import org.junit.Test;

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

public class DemoDaoTest {
	private DemoDao demoDao=new DemoDao();
	/**
	 * 两个都可以同时添加
	 * 添加订单的时候,也把订单项添加进来了
	 * 而且只调用了一个dao方法
	 */
	@Test
	public void testAddOrder() {
		Order order=new Order();
		order.setOrder_no("T235购物");
		for (int i = 0; i < 6; i++) {
			OrderItem orderItem=new OrderItem();
			orderItem.setProduct_id(20+i);
			orderItem.setQuantity(40+i);
			order.getOrderItems().add(orderItem);
			orderItem.setOrder(order);
		}
		demoDao.addOrder(order);
	}
/**
 * 添加订单项
 */
	@Test
	public void testAddOrderItem() {
		OrderItem orderItem=new OrderItem();
		orderItem.setProduct_id(666);
		orderItem.setQuantity(666);
		Order order=new Order();
		order.setOrder_id(11);
		orderItem.setOrder(order);
		demoDao.addOrderItem(orderItem);
	}
/**
*查询订单,利用了懒加载也可以强制加载关联关系 查看订单项的信息
*/

	@Test
	public void testGetOrder() {
		Order order=new Order();
		order.setOrder_id(10);
		order.setInitChildren(1);
		
	Order  o=demoDao.getOrder(order);
	System.out.println(o.getOrder_no());
	System.out.println(o.getOrderItems());
	}

	@Test
	public void testGetOrderList() {
		List<Order> orderList = demoDao.getOrderList();
		for (Order order : orderList) {
			System.out.println(order.getOrder_no());
			System.out.println(order.getOrderItems().size());
		}
		
		
	}
/**
 * 订单和订单项会同时删除
 */
	@Test
	public void testDelOrder() {
		Order order=new Order();
		order.setOrder_id(11);
		this.demoDao.delOrder(order);
	}

}

这个课程的重点:懒加载
在实体类多加了一个字段,默认为0
//0代表默认懒加载,1代表强制加载
在DemoDao中的getOrder()方法添加一段代码 ,强制加载关联关系
//强制加载关联关系
if(o != null && new Integer(1).equals (order.getInitChildren())) {
Hibernate.initialize(o.getOrderItems());
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值