hibernate关联关系(一对多)
程序员文章站
2022-04-22 22:20:28
...
hibernate关联关系(一对多)
什么是关联
关联指的是类之间的引用关系。如果类A与类B关联,那么被引用的类B将被定义为类A的属性。例如:
class B{
private String name;
}
public class A{
private B b = new B;
public A(){}
}
案例
订单与订单项的一对多的增删改查
Order
一个订单包含多个订单项
package com.shl.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
每个订单项都有对应的订单
package com.shl.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
<?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.shl.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.shl.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.shl.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.shl.three.entity.Order" column="oid"></many-to-one>
</class>
</hibernate-mapping>
DemoDao
package com.shl.three.dao;
import java.util.List;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.shl.three.entity.Order;
import com.shl.three.entity.OrderItem;
import com.shl.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
利用junit进行测试
package com.shl.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.shl.three.entity.Order;
import com.shl.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.shl.three.entity.Order,以及t_hibernate_order
类属性,以及表列段
5.生成动态sql
执行sql最终得到meterData(源数据模型)
6.Order o1 = Class.forName("com.shl.three.entity.Order").newInstance(0);
o1.set...
...
最终得到:
List<Order> list=new arr..
list.add(o1);
..
最终list中所有order实例都有值了(这里只是处理表面的非外键列段,原理完全跟baseDao一样)
7.处理关联关系 orderitems oid com.shl.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时:不是懒加载,默认为懒加载
获取订单表的内容时,如果lazy为true,就只能获取订单表的内容,获取不到对应订单项的内容。要想获取到对应订单项的内容,需要强制加载关联对象。
Hibernate.initialize(o.getOrderitems());
如果lazy为false,就会自动获取到对应订单项的内容,就很方便。
但是出于性能的考虑,所有lazy默认为true,看情况自己设置。
上一篇: css设置悬浮列表样式_如何使用CSS设置列表样式
下一篇: 03. 关联关系映射(一对一)