1. 什么是关联(association)
1.1 关联指的是类之间的引用关系。如果类A与类B关联,那么被引用的类B将被定义为类A的属性。例如:
1.2 关联的分类:关联可以分为一对一、一对多/多对一、多对多关联

新建实体类关联关系:Order

package com.zl.three.entity;

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

public class Order {
	private Integer orderId;
	private String orderNo;
	//建立了关联关系 一个订单对应了多个订单项
	private List<OrderItem> OrderItems = new ArrayList<>();
	private Integer initChildren = 0;//懒加载
	
	 
	public Integer getInitChildren() {
		return initChildren;
	}
	public void setInitChildren(Integer initChildren) {
		this.initChildren = initChildren;
	}
	public List<OrderItem> getOrderItems() {
		return OrderItems;
	}
	public void setOrderItems(List<OrderItem> orderItems) {
		OrderItems = orderItems;
	}
	public Integer getOrderId() {
		return orderId;
	}
	public void setOrderId(Integer orderId) {
		this.orderId = orderId;
	}
	public String getOrderNo() {
		return orderNo;
	}
	public void setOrderNo(String orderNo) {
		this.orderNo = orderNo;
	}
	@Override
	public String toString() {
		return "Order [orderId=" + orderId + ", orderNo=" + orderNo + "]";
	}
	
}

  

在映射文件中进行关联关系的维护

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.zl.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="false" name="orderItems" cascade="save-update" inverse="true" >
			<key column="oid"></key>
			<one-to-many class="com.zl.three.entity.OrderItem"/>
		</bag>
	</class>

</hibernate-mapping>

  

OrderItem

package com.zl.three.entity;

public class OrderItem {
	private Integer orderItemId;
	private Integer productId;
	private Integer quantity;
	private Integer oid;
	//建立关联关系 一个订单项对应的是一个订单
	private Order order;
	
	public Order getOrder() {
		return order;
	}
	public void setOrder(Order order) {
		this.order = order;
	}
	public Integer getOrderItemId() {
		return orderItemId;
	}
	public void setOrderItemId(Integer orderItemId) {
		this.orderItemId = orderItemId;
	}
	public Integer getProductId() {
		return productId;
	}
	public void setProductId(Integer productId) {
		this.productId = productId;
	}
	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;
	}
	@Override
	public String toString() {
		return "OrderItem [orderItemId=" + orderItemId + ", productId=" + productId + ", quantity=" + quantity
				+ ", oid=" + oid + "]";
	}
	
}

  

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.zl.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.zl.three.entity.Order" column="oid">
		</many-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://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
	<session-factory>
		<!-- 1. 数据库相关 -->
		<property name="connection.username">root</property>
		<property name="connection.password">123</property>
		<property name="connection.url">jdbc:mysql://localhost:3306/db_0601?useUnicode=true&characterEncoding=UTF-8
		</property>
		<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
		<!-- <property name="dialect">org.hibernate.dialect.MySQLDialect</property> -->
		<property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
		<property name="hbm2ddl.auto">update</property>
		<!-- 配置本地事务(No CurrentSessionContext configured!) -->
		<property name="hibernate.current_session_context_class">thread</property>
		<!-- 2. 调试相关 -->
		<property name="show_sql">true</property>
		<property name="format_sql">true</property>
		<!-- 3. 添加实体映射文件 -->
		<mapping resource="com/zl/one/entity/User.hbm.xml" />
		<!-- 主键生成策略 -->
		<mapping resource="com/zl/two/entity/Worker.hbm.xml" />
		<mapping resource="com/zl/two/entity/Student.hbm.xml" />
		<!-- 一对多 -->
		<mapping resource="com/zl/three/entity/OrderItem.hbm.xml" />
		<mapping resource="com/zl/three/entity/Order.hbm.xml" />
	</session-factory>
</hibernate-configuration>

  

测试:DemoDao

package com.zl.three.DemoDao;

import java.util.List;

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

import com.zl.three.entity.Order;
import com.zl.three.entity.OrderItem;
import com.zl.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;
	}
	
	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.zl.three.DemoDao;

import java.util.List;

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

import com.zl.three.entity.Order;
import com.zl.three.entity.OrderItem;
/**
 * @Before每测试一个@Test标记的测试方法,都会调用之前执行一次
 * @After每测试一个@Test标记的测试方法,都会调用之后执行一次
 * @author zl
 *
 */
public class DemoDaoTest {
	private DemoDao demoDao = new DemoDao();
	/*@Before
	public void setUp() throws Exception {
	}

	@After
	public void tearDown() throws Exception {
	}*/

	@Test
	public void testAddOrder() {
		Order order = new Order();
		order.setOrderNo("p20");
		OrderItem orderItem = new OrderItem();
		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(22);
		orderItem.setQuantity(11);
		Order order = new Order();
		order.setOrderId(2);
		order.getOrderItems().add(orderItem);
		orderItem.setOrder(order );
		demoDao.addOrderItem(orderItem);
	}

	@Test
	public void testGetOrder() {
		Order order = new Order();
		order.setOrderId(1);
//		order.setInitChildren(1);
		Order order2 = this.demoDao.getOrder(order);
//		当lazy=false的时候,会让hibernate执行完两次操作,session才会关闭
		//出于性能的考虑,所用hibernate3.0出现lazy这个属性,也就是说吧加载关联属性 
//		List<OrderItem> orderItems = order2.getOrderItems();
//		for (OrderItem orderItem : orderItems) {
//			System.out.println(orderItem);
//		} 
		System.out.println(order2);
	}

	@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(2);
		this.demoDao.delOrder(order);
	}
  }

  

 

 

posted on 2019-08-04 19:56  八友  阅读(136)  评论(0编辑  收藏  举报