Hibernate关联关系(一对多)
1. 什么是关联(association)
关联指的是类之间的引用关系。如果类A与类B关联,那么被引用的类B将被定义为类A的属性。
例如:
class B{
private String name;
}
public class A{
private B b = new B;
public A(){}
}
2.Set元素中的cascade|inverse|outter-join|lazy属性作用
2.1 lazy:默认值为true,true延迟加载,false立即加载(一般设置为true,不使用立即加载,因为影响查询性能)
2.2 outter-join:默认值为false,true使用左外联接查询关联的(但一般不用,因为当我们把该属性设置为true时,所有的查询语句都会默认左外联,那样性能不高)
2.3 inverse:默认值为false,true表示将对方设置为主控方(一对多双向关联中一般将多方设置为主控方,这样可以减少SQL语句的数量,减少多余的操作)
2.4 cascade:用来控制如何操作关联的持久化对象的
2.4.1 none:保存,更新或删除当前对象时,忽略其它关联的对象
2.4.2 save-update:保存、更新时级联保存所有的临时对象,并且级联更新关联的游离对象
2.4.3 delete:通过session的delete方法删除当前对象,级联删除关联的对象
2.4.4 all:等于save-update操作+delete操作
3. 案例:如何建立客户和订单一对多双向关联
工具类SessionFactoryUtils.java
package com.lzy.two.uity;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/**
* 本工具类的作用:
* 1.简化代码的书写
* 2.检测hibernate相关的配置是否正确
* @author
*
*/
public class SessionFactoryUtils {
private static SessionFactory sessionFactory;
static {
Configuration cfg = new Configuration().configure("hibernate.cfg.xml");
sessionFactory = cfg.buildSessionFactory();
}
public static Session openSession() {
Session session = sessionFactory.getCurrentSession();
if(session == null) {
session = sessionFactory.openSession();
}
return session;
}
public static void closeSession() {
Session session = sessionFactory.getCurrentSession();
if(session != null && session.isOpen()) {
session.close();
}
}
public static void main(String[] args) {
Session session = SessionFactoryUtils.openSession();
session.beginTransaction();
System.out.println(session.isConnected());
SessionFactoryUtils.closeSession();
System.out.println(session.isConnected());
}
}
实体类Order.java
package com.lzy.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 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 List<OrderItem> getOrderItems() {
return orderItems;
}
public void setOrderItems(List<OrderItem> orderItems) {
this.orderItems = orderItems;
}
@Override
public String toString() {
return "Order [orderId=" + orderId + ", orderNo=" + orderNo + ", orderItems=" + orderItems + "]";
}
}
OrderItem.java
package com.lzy.three.entity;
public class OrderItem {
private Integer orderItemId;
private Integer productId;
private Integer quantity;
private Integer oid;
private 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 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.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.lzy.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标签
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.lzy.three.entity.OrderItem"></one-to-many>
</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.lzy.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 :指的是当前所要映射的类com.lzy.three.entity.OrderItem的关联属性order
class :指的是关联属性的类别(全路径名)
column :指的是外键
-->
<many-to-one name="order" class="com.lzy.three.entity.Order" column="oid"></many-to-one>
</class>
</hibernate-mapping>
配置hibernate.cfg.xml
package com.lzy.three.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.lzy.three.entity.Order;
import com.lzy.three.entity.OrderItem;
import com.lzy.two.uity.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;
}
/**
* 主表的数据不能随便删除,得先删除从表中对应信息,才能删除主表的信息。
* @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.java
package com.lzy.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.lzy.three.entity.Order;
import com.lzy.three.entity.OrderItem;
public class DemoDaoTest {
private DemoDao demoDao=new DemoDao();
@Test
public void testAddOrder() {
Order order=new Order();
order.setOrderNo("炸鸡翅");
for (int i = 0; i < 3; i++) {
OrderItem oi=new OrderItem();
oi.setProductId(6+i);
oi.setQuantity(15+i);
order.getOrderItems().add(oi);
oi.setOrder(order);
}
demoDao.addOrder(order);
}
@Test
public void testAddOrderItem() {
OrderItem oi=new OrderItem();
oi.setProductId(1);
oi.setQuantity(68);
Order order=new Order();
order.setOrderId(11);
oi.setOrder(order);
demoDao.addOrderItem(oi);
}
}
4.懒加载
意义:懒加载的主要目的就是作为服务器前端的优化,减少请求次数或者延迟请求数。
实现原理: 先加载一部分数据,当触发某个条件时利用异步加载剩余的数据,新得到的数据不会影响原有数据的显示,同时最大幅度的减少服务器端资源耗用。
在Order实体类中加入以下属性
private Integer initChildren = 1;//0代表默认懒加载 1代表强制加载
public Integer getInitChildren() {
return initChildren;
}
public void setInitChildren(Integer initChildren) {
this.initChildren = initChildren;
}
方法
/**
* 为了讲解懒加载的问题(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;
}
测试
/**
* 懒加载
*/
@Test
public void testGetOrder() {
Order order=new Order();
order.setOrderId(11);
order.setInitChildren(1);
Order o=demoDao.getOrder(order);
//failed to lazily initialize a collection of role:
//com.lzy.three.entity.Order.orderItems, could not initialize proxy - no Session
System.out.println(o.getOrderNo());
System.out.println(o.getOrderItems().size());
}
@Test
public void testGetOrderList() {
List<Order> orders=demoDao.getOrderList();
for (Order order : orders) {
System.out.println(order.getOrderNo());
}
}