什么是关联关系
关联指的是类之间的引用关系。如果类A与类B关联,那么被引用的类B将被定义为类A的属性
比如,B类作为A类的一个属性,那么就是B与A有关联关系
class B{
private String name;
}
public class A{
private B b = new B;
public A(){}
}
关联关系主要有:一对一、一对多/多对一、多对多关联
Hibernate的orm框架、主要是以面向对象的思想操作数据库
Hibernate实现订单与订单项的一对多的增删改查
数据库表结构(一对多,订单表、订单项表):
-- 订单表(主表)
create table t_hibernate_order
(
order_id int primary key auto_increment,
order_no varchar(50) not null
);
-- 订单项表(从表)
create table t_hibernate_order_item
(
order_item_id int primary key auto_increment,
product_id int not null,
quantity int not null,
oid int not null,
foreign key(oid) references t_hibernate_order(order_id)
);
实体类(持久化类) Order.java
lazy这个参数,就是是否开启懒加载模式,为了提高性能,我们在实体类中定义了一个属性来控制是否开启懒加载模式(懒加载模式结尾有解释)
package com.Tang.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;//0是懒加载 1,false
public Integer getInitChildren() {
return InitChildren;
}
public void setInitChildren(Integer initChildren) {
InitChildren = initChildren;
}
public List<OrderItem> getOrderitems() {
return orderitems;
}
public void setOrderitems(List<OrderItem> orderitems) {
this.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 + "]";
}
}
OrderItem.java(每个订单项都有对应的订单)
package com.Tang.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 + "]";
}
}
Order.hbm.xml
oid是外键的oid
<?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.Tang.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
cascade:级联关系 级联新增与修改
name:类的关联属性
inverse: 关联关系交给对方控制 默认是true,当前类不维护关联关系
子标签key:
column:主表的主键,从表的外键
子标签one-to-many:
class: 外键对应的实体类
-->
<bag name="orderitems" lazy="true" cascade="save-update" inverse="true">
<key column="oid"></key>
<one-to-many class="com.Tang.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.Tang.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.Tang.three.entity.Order" column="oid"></many-to-one>
</class>
</hibernate-mapping>
DemoDao
package com.Tang.three.dao;
import java.util.List;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;
import com.Tang.three.entity.Order;
import com.Tang.three.entity.OrderItem;
import com.Tang.three.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(利用junit进行测试)
package com.Tang.three.dao;
import static org.junit.Assert.*;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.Tang.three.entity.Order;
import com.Tang.three.entity.OrderItem;
/**
* @Before没测试一个@Test标记的方法,都会执行一次
* @After没测试一个@Test标记的方法,都会调用之后执行一次
* @author Administrator
*
*/
public class DemoDaoTest {
private DemoDao dd=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 o=new Order();
o.setOrderNo("p30");
OrderItem oi=null;
for (int i = 0; i < 8; i++) {
oi=new OrderItem();
oi.setProductId(10+i);
oi.setQuantity(99+i);
//维护关联关系
oi.setOrder(o);
o.getOrderitems().add(oi);
}
dd.addOrder(o);
}
@Test
public void testAddOrderItem() {
OrderItem oi=null;
for (int i = 0; i < 8; i++) {
oi=new OrderItem();
oi.setProductId(88+i);
oi.setQuantity(22+i);
//维护关联关系
Order o=new Order();
o.setOrderId(1);
o.getOrderitems().add(oi);
oi.setOrder(o);
dd.addOrderItem(oi);
}
}
@Test
public void testGetOrder() {
Order order=new Order();
order.setOrderId(1);
order.setInitChildren(1);
Order o = this.dd.getOrder(order);
List<OrderItem> ois=o.getOrderitems();
//当lazy=false时,会让hibernate执行两次操作,session才会关闭,将关联表中的数据查出来
//当lazy=true时,会让hibernate执行一次操作,session就会关闭
//但是出于性能的考虑,所有lazy默认为true
for (OrderItem orderItem : ois) {
System.out.println(orderItem);
}
System.out.println(o);
}
@Test
public void testGetOrderList() {
List<Order> orderList = this.dd.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.dd.delOrder(order);
}
}
Hibernate框架一对多的执行原理
1.对hibernate.cfg.xml进行建模,等到sessionFactory对象
2.并且拿到了mapping resource里的内容
3.拿到了Order.hbm.xml配置文件
4.可以再次建模,拿到com.Tang.three.entity.Order,以及t_hibernate_order
类属性,以及表列段
5.生成动态sql
执行sql最终得到meterData(源数据模型)
6.Order o1 = Class.forName("com.Tang.three.entity.Order").newInstance(0);
o1.set...
...
最终得到:
List<Order> list=new arr..
list.add(o1);
..
最终list中所有order实例都有值了(这里只是处理表面的非外键列段,原理完全跟baseDao一样)
7.处理关联关系 orderitems oid com.Tang.three.entity.OrderItem
通过one-to-many这个标签以及class对应的全路径名会找到对class对应的全路径名对应的专属映射文件
也就是找到了 OrderItem.hbm.xml,拿到他之后就可以拿到t_hibernate_order_item
8.select * from t_hibernate_order_item;
最终得到了一个List<OrderItem> ois
9.给order的关联关系属性赋值
List<Order> list=new arr..
for(Order o:list){
o.setOrderItem(ois);
}
懒加载
在配置Order.hbm.xml时,有一个lazy的属性,就是是否开启懒加载模式,当lazy=true时:懒加载,当lazy=false时:不是懒加载,默认为懒加载
在test测试类方法中添加order.setInitChildren(1或0),是否给它设置强制加载
在这里想要获取订单表的内容时,如果lazy为true,就只能获取订单表的内容,获取不到对应订单项的内容。要想获取到对应订单项的内容,需要强制加载关联对象
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());
}
transaction.commit();
session.close();
return o;
}