hibernate关联关系(一对多)
1.什么是关联关系?
关联关系是指两个实体或者表有相互关联,比如在订单表中,订单项表有订单id,那么订单项表中的订单id就关联订单项表中订单Id字段。因此关联关系,可以看成是一种外键关系。
2.为什么要有关联关系?
为了实现级联操作,删除订单中某个列段,会连带删除订单项表中相对应的列段,以便维护表数据的一致性。
配置文件:
SessionFactoryUtils
package com.chenjiahao.two.util;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
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
package com.chenjiahao.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,fasle
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) {
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.chenjiahao.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 + "]";
}
}
配置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/T224?useUnicode=true&characterEncoding=UTF-8
</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</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/chenjiahao/one/entity/User.hbm.xml"/>
<!-- 讲解主键生成 策略-->
<mapping resource="com/chenjiahao/two/entity/Student.hbm.xml"/>
<mapping resource="com/chenjiahao/two/entity/Worker.hbm.xml"/>
<!-- 一对多 -->
<mapping resource="com/chenjiahao/three/entity/OrderItem.hbm.xml"/>
<mapping resource="com/chenjiahao/three/entity/Order.hbm.xml"/>
</session-factory>
</hibernate-configuration>
实体类xml配置文件:
bag标签:
lazy:是否懒加载,默认是懒加载的 true
name:类的关联属性名
cascade:级联关系 级联新增与修改
inverse:关联关系交给对方控制默认是true,当前类不维护关联关系
子标签key:
column:主表的主键,从标的外键
子标签one-to-many:外键对应的实体类
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.chenjiahao.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="orderItems" cascade="save-update" inverse="true">
<key column="oid"></key>
<one-to-many class="com.chenjiahao.three.entity.OrderItem"/>
</bag>
</class>
</hibernate-mapping>
OrderItem.hbm.xml
insert="fasle' update ="fasle" 这个属性只能给一个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.chenjiahao.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>
<!-- Repeated column in mapping for entity -->
<property name="oid" type="java.lang.Integer" column="oid" insert="false" update="false">
</property>
<many-to-one name="order" class="com.chenjiahao.three.entity.Order" column="oid"></many-to-one>
</class>
</hibernate-mapping>
DemoDao
package com.chenjiahao.three.dao;
import java.util.List;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.chenjiahao.three.entity.Order;
import com.chenjiahao.three.entity.OrderItem;
import com.chenjiahao.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
package com.chenjiahao.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.chenjiahao.three.entity.Order;
import com.chenjiahao.three.entity.OrderItem;
/**
* @Before每测试一个@test标记的测试方法,都会调用之前执行一次
* @After每测试一个@test标记的测试方法,都会调用之后执行一次
* @author dell
*
*/
public class DemoDaoTest {
private DemoDao demoDao=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 order=new Order();
order.setOrderNo("honor20");//订单编号,因为id是自增列不用管
OrderItem orderItem =null;
for (int i = 0; i < 6; i++) {
orderItem = new OrderItem();
orderItem.setProductId(19+i);
orderItem.setQuantity(26+i);
//维护关系
orderItem.setOrder(order);//给订单项里面的属性赋值
order.getOrderItems().add(orderItem);
}
demoDao.addOrder(order);
}
@Test//给原有的订单表添加订单项
public void testAddOrderItem() {
//添加一条数据
// OrderItem orderItem = new OrderItem();
// orderItem.setProductId(12);
// orderItem.setQuantity(41);
// Order order=new Order();
// order.setOrderId(2);
// order.getOrderItems().add(orderItem);
// orderItem.setOrder(order);
// demoDao.addOrderItem(orderItem);
//添加多条数据
OrderItem orderItem = null;
for (int i = 0; i < 6; i++) {
orderItem = new OrderItem();
orderItem.setProductId(10+i);
orderItem.setQuantity(20+i);
//维护关系
Order order=new Order();
order.setOrderId(2);//订单id
order.getOrderItems().add(orderItem);
orderItem.setOrder(order);
demoDao.addOrderItem(orderItem);
}
}
@Test
public void testGetOrder() {
Order order = new Order();
order.setOrderId(3);
order.setInitChildren(1);
Order o = this.demoDao.getOrder(order);
//failed to lazily initialize a collection of role:
//com.chenjiahao.three.entity.Order.orderItems,
//could not initialize proxy - no Session
//原因:操作了两次数据库,当layz等于false的时候,会让hibernate执行两次操作,session才会关闭
//当layz等于true的时候,会让hibernate执行一次操作,session就会关闭
//从上面看layz等于false更好,但是为什么hibernate默认让它等于true?
//处于性能的考虑,所以hibernate3.0出现lazy这个属性,并让它默认等于true,也就是说不加载关联属性
List<OrderItem> orderItems = o.getOrderItems();
for (OrderItem orderItem : orderItems) {
System.out.println(orderItem);
}
System.out.println("id为3的订单:"+o);
}
@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);
}
}
懒加载:
只有在使用时,他才会发出SQL语句,查询数据,如果不使用对象则不会发出SQL语句进行查询。
Hibernate的lazy生效期:
生效期和session一样的,session关闭,lazy失效
hibernate支持lazy策略只在session打开状态下有效
@Test
public void testGetOrder() {
Order order = new Order();
order.setOrderId(3);
order.setInitChildren(1);
Order o = this.demoDao.getOrder(order);
//failed to lazily initialize a collection of role:
//com.chenjiahao.three.entity.Order.orderItems,
//could not initialize proxy - no Session
//原因:操作了两次数据库,当layz等于false的时候,会让hibernate执行两次操作,session才会关闭
List<OrderItem> orderItems = o.getOrderItems();
for (OrderItem orderItem : orderItems) {
System.out.println(orderItem);
}
System.out.println("id为3的订单:"+o);
}
在order类中(也就是主表)加一个属性:
private Integer initChildren=0;//0是懒加载 1,fasle
在domedao类里的get加:
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;
}
从而可以控制是否懒加载
hibernate框架一对多的执行原理:
1、对hibernate.cfg.xml进行建模,等到sessionfactory对象
2、并且拿到mapping resoutrce里的内容
3、拿到了Order.hbm.xml配置文件
4、可以再次建模,拿到com.chenjiahao.three.entity.Order(实体类),以及t_hibernate_order(数据库表名)
类属性,以及表列段
5、生成动态的sql:select ordeerId,orderNo from t_hibernate_order;
执行sql最终得到meterDate源数据模型
ordeerId,orderNo
1 p20
3 p30
6、Order o1=Class.forName().newInstance();
o1.setOrderId(1);
o1.setOrderNo(p1);
.....
最终得到:
List<Order> List=new ArrayList();
List.add(01);
...
最终list中的所有order实列都有值了:(这里只是处理表里的非外加列段,原理完全跟baseDao一样)
7、处理关联关系:(通过建模可以得到Order.hbm.xml所有的属性)orderItems oid com.chenjiahao.three.entity.OrderItem
通过one-to-many这个标签以及calss对应的全路径名对应的专属映射文件
也就是找到了Order.item.xml文件,拿到了它之后就可以拿到table t_hibernate_order_item
8、select * from t_hibernate_order_item;
最终得到一个list<OrderItem> orderItems
9、 给order的关联关系属性赋值
List<Order> List=new ArrayList();
for(Order o: list){
o.setOrderItems(orderItems);
}

浙公网安备 33010602011771号