Hibernate 关联关系(一对多)

Hibernate 关联关系(一对多)

1. 什么是关联(association)

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

private String name;

private List<A> bs = new arraylist();
    }

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

      }
}
hibernate:orm框架、以面向对象的思想操作数据库

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

案列:

导入映射文件Order.hbm.xml和OrderItem.hbm.xml

Order.hbm.xm

进行关联关系的维护一对多的关系

Hibernate 关联关系(一对多)

OrderItem.hbm.xml

进行关联关系的维护 一对多的关系

Hibernate 关联关系(一对多)

hibernate.cfg.xml(核心配置文件)添加映射文件OrderItem.hbm.xml和Order.hbm.xm

Hibernate 关联关系(一对多)

 对应映射文件的实体类

Order.hbm.xml

Order 
 package com.MavenHibernate.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<>(); public List<OrderItem> getOrderItems() {
return orderItems;
} public void setOrderItems(List<OrderItem> orderItems) {
this.orderItems = orderItems;
} public List<OrderItem> getOrderItem() {
return orderItems;
} public void setOrderItem(List<OrderItem> orderItem) {
this.orderItems = orderItem;
}
@Override
public String toString() {
return "Order [orderId=" + orderId + ", orderNo=" + orderNo + ", orderItem=" + 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;
}
public Order(Integer orderId, String orderNo) {
super();
this.orderId = orderId;
this.orderNo = orderNo;
}
public Order() {
super();
} }

OrderItem.hbm.xml

OrderItem

 package com.MavenHibernate.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;
}
@Override
public String toString() {
return "OrderItem [orderItemId=" + orderItemId + ", productId=" + productId + ", quantity=" + quantity
+ ", oid=" + oid + ", 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;
}
public OrderItem(Integer orderItemId, Integer productId, Integer quantity, Integer oid) {
super();
this.orderItemId = orderItemId;
this.productId = productId;
this.quantity = quantity;
this.oid = oid;
}
public OrderItem() {
super();
} }

测试:

DemoDao 
 package com.MavenHibernate.three.Dao;

 import java.util.List;

 import org.hibernate.Session;
import org.hibernate.Transaction; import com.MavenHibernate.three.entity.Order;
import com.MavenHibernate.three.entity.OrderItem;
import com.MavenHibernate.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();
}
}

利用junit进行DemoDao测试

DemoDaoTest

 package com.MavenHibernate.three.Dao;

 import static org.junit.Assert.*;

 import org.junit.Before;
import org.junit.Test; import com.MavenHibernate.three.entity.Order;
import com.MavenHibernate.three.entity.OrderItem; public class DemoDaoTest { private DemoDao demoDao=new DemoDao(); @Before
public void setUp() throws Exception {
} @Test
public void testAddOrder() {
Order order = new Order();
order.setOrderNo("226");
OrderItem oi=null;
for (int i = 0; i < 3; i++) {
oi = new OrderItem();
oi.setProductId(10+i);
oi.setQuantity(20+i);
oi.setOrder(order);
order.getOrderItems().add(oi); }
demoDao.addOrder(order);
} //订单项
@Test
public void testAddOrderItem() {
Order order = new Order();
order.setOrderId(5);
OrderItem oi=null;
for (int i = 0; i < 3; i++) {
oi = new OrderItem();
oi.setProductId(10+i);
oi.setQuantity(20+i);
oi.setOrder(order);
order.getOrderItems().add(oi);
demoDao.addOrderItem(oi); }
} }

结果:

Hibernate 关联关系(一对多)

Hibernate 关联关系(一对多)

Hibernate 关联关系(一对多)

订单项

Hibernate 关联关系(一对多)

Hibernate 关联关系(一对多)

2.懒加载

DemoDaoTest

Hibernate 关联关系(一对多)

运行时控制台会报一个这样的错误:

Hibernate 关联关系(一对多)

处理方式:(第一种)
在对应实体映射文件中的关联关系的维护中添加 lazy="false"

Hibernate 关联关系(一对多)

处理方式:(第二种)
   在一对多的实体类中添加属性是否打开懒加载

 在order实体类中

Hibernate 关联关系(一对多)

 DemoDao中的懒加载方法

Hibernate 关联关系(一对多)

 DemoDaoTest

 package com.MavenHibernate.three.Dao;

 import static org.junit.Assert.*;

 import java.util.List;

 import org.junit.Before;
import org.junit.Test; import com.MavenHibernate.three.entity.Order;
import com.MavenHibernate.three.entity.OrderItem; public class DemoDaoTest { private DemoDao demoDao=new DemoDao(); public void setUp() throws Exception {
} @Test
public void testAddOrder() {
Order order = new Order();
order.setOrderNo("226");
OrderItem oi=null;
for (int i = 0; i < 3; i++) {
oi = new OrderItem();
oi.setProductId(10+i);
oi.setQuantity(20+i);
oi.setOrder(order);
order.getOrderItems().add(oi); }
demoDao.addOrder(order);
} //订单项
@Test
public void testAddOrderItem() {
Order order = new Order();
order.setOrderId(5);
OrderItem oi=null;
for (int i = 0; i < 3; i++) {
oi = new OrderItem();
oi.setProductId(10+i);
oi.setQuantity(20+i);
oi.setOrder(order);
order.getOrderItems().add(oi);
demoDao.addOrderItem(oi); }
} /**
* 关于懒加载的问题
* hibernate3之后出现的
* failed to lazily initialize a collection of role:
* com.MavenHibernate.three.entity.Order.orderItems, could not initialize proxy - no Session
* * orderNo数据来源于t_hibernate_order表
* orderItems数据来源于t_hibernate_order_item表
*
* 因为两表有关联关系所以不可以分开查询,
* 而hibernate默认的策略是不查询关联关系对应关联表数据的
*
* 处理方式:(第一种)
* 在对应实体映射文件中的关联关系的维护中添加 lazy="false"
* 如:<bag lazy="false" name="orderItems" cascade="save-update" inverse="true">
*/ @Test
public void testGetOrder() {
Order order = new Order();
order.setOrderId(10);
//关闭懒加载
order.setInitChildren(0);
Order o = this.demoDao.getOrder(order);
System.out.println(o.getOrderNo());
System.out.println(o.getOrderItems());
} /**
* 查询多个
* 在查询单个中懒加载问题的解决方案
* 会导致在查询多个的时候sql语句也会增多,
* 当查询数据过多的时候导致代码性能变低
*
* 总:如果将懒加载的功能关闭,即:lazy=false,
* 那么在查询多条订单数据的情况下是非常影响性能的
*
* 查单个需要关闭懒加载 目的是需要加载出关联表的数据
* 查多个不能关闭懒加载 加载关联表的数据的查询次数过多
*
* 处理方式:(第二种)
* 在一对多的实体类中添加属性是否打开懒加载
*
*/
@Test
public void testGetOrderList() {
List<Order> orderList = this.demoDao.getOrderList();
for (Order order : orderList) {
System.out.println(order.getOrderNo());
// System.out.println(order.getOrderItems());
}
}
/**
* 删除订单,关联关系同时删除
*/
@Test
public void testDelOrder() {
Order order = new Order();
order.setOrderId(10);
this.demoDao.delOrder(order);
} }
上一篇:asp.net mvc核心、实体框架和simplepagin .js中的分页


下一篇:1.异步消息Jms及其JmsTemplate的源代码分析,消息代理ActiveMQ