什么是关联?(association)
关联指的是类之间的引用关系。如果类A与类B关联,那么被引用的类B将被定义为类A的属性。例如:
class B{ private String name; } public class A{ private B b = new B; public A(){} }
关联的分类:
关联可以分为一对一、一对多/多对一、多对多关联
关联是有方向的
HIbernate一对多的实现
1.在数据库中建好测试的表(这里用的MYSQL)
表的实体类:
package com.psy.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 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 + "]"; } }
package com.psy.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配置:
<class name="com.psy.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:类的关联属性名 cascade:级联关系 级联新增修改 inverse:关联关系交给对方控制 默认值:true( 当前类不维护关联关系) 子标签key: column:从表的外键 子标签one-to-many: class:外键对应的实体类 --> <bag lazy="false" name="orderItems" cascade="save-update" inverse="true"> <key column="oid"></key> <one-to-many class="com.psy.three.entity.OrderItem" /> </bag> </class>
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.psy.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.psy.three.entity.Order" column="oid"> </many-to-one> </class> </hibernate-mapping>
hibernate.cfg.xml主配置文件:
<!-- 一对多--> <mapping resource="com/psy/three/entity/OrderItem.hbm.xml" /> <mapping resource="com/psy/three/entity/Order.hbm.xml" />
dao方法:
package com.psy.three.dao; import java.util.List; import org.hibernate.Session; import org.hibernate.Transaction; import com.psy.three.entity.Order; import com.psy.three.entity.OrderItem; import com.psy.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.psy.three.dao; import static org.junit.Assert.*; import java.util.List; import org.hibernate.Session; import org.hibernate.Transaction; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.psy.three.entity.Order; import com.psy.three.entity.OrderItem; import com.psy.two.util.SessionFactoryUtils; /** * setUp每测试一个@test标记的测试方法,都会在调用之前执行一次 tearDown每测试一个@test标记的测试方法,都会在调用之后执行一次 * * @author Admin * */ public class DemoDaoTest { private DemoDao demodao = new DemoDao(); // @Before // public void setUp() throws Exception { // System.out.println("加载资源"); // Session session = SessionFactoryUtils.openSession(); // Transaction transaction = session.beginTransaction(); // // } // // @After // public void tearDown() throws Exception { // System.out.println("释放资源"); // transaction.commit(); // session.close(); // // } @Test public void testAddOrder() { Order order = new Order(); order.setOrderNo("P20"); OrderItem orderItem = null; for (int i = 0; i < 6; i++) { orderItem = new OrderItem(); orderItem.setProductId(10 + i); orderItem.setQuantity(20 + i); //维护关联关系 orderItem.setOrder(order); order.getOrderItems().add(orderItem); } demodao.addOrder(order);//只调用了一个新增的dao方法 可以增加两个表的数据 } @Test public void testAddOrderItem() { OrderItem orderItem = new OrderItem(); for (int i = 0; i < 6; i++) { orderItem = new OrderItem(); orderItem.setProductId(10 + i); orderItem.setQuantity(20 + i); //维护关联关系 Order order=new Order(); order.setOrderId(1); order.getOrderItems().add(orderItem); orderItem.setOrder(order); demodao.addOrderItem(orderItem); } } @Test public void testGetOrder() { Order order= new Order(); order.setOrderId(1); Order o = this.demodao.getOrder(order); //操作了两次数据库 当lazy=false的时候 会让hibernate执行完两次操作,session才会关闭 //当lazy=true的时候hibernate执行一次就会关闭 //从上面看lazy=false更好 但是为什么默认让它等于true //出于性能的考虑,所有hibernate3.0出现了lazy这个属性,并让它默认等于true 也就是说不加载关联属性 List<OrderItem> orderItems = o.getOrderItems(); for (OrderItem orderItem : orderItems) { System.out.println(orderItem); } System.out.println(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(1); this.demodao.delOrder(order );//调用一个dao方法 可以同时删除两个表的数据(主表的数据不能随便删除,得先删除从表中对应信息,才能删除主表的信息) } }
hibernate框架一对多的执行原理:
1.对hibernate.cfg.xml进行建模,等到sessionfactory对象
2.并且拿到mapping resource里的内容
3.拿到了Order.hbm.xml配置文件
4.可以再次建模,拿到了com.psy.three.entity.Order,以及t_hibernate_order
类属性、以及表列段
5.生成动态的SQL:select orderNo,orderId from t_hibernate_order
执行SQL最终得到meterDate源数据模型
Order o1= Class.forName("com.psy.three.entity.Order")
o2.setOrderId(1)
o2.setOrderNo(P1)
......
最终得到:
List<Order> list=new ArrayList();
list.add(01);
.....
最终list中所有的order实例都有值了(这里只是处理了表里的非外键列段,原理同baseDao)
7.处理关联关系:orderItems oid com.psy.three.entity.OrderItem
通过one-to-many这个标签以及class对应全路径名会找到class对应的全路径名的专属映射文件
也就是找到了order.item.xml这个文件,拿到了它之后就可以拿到table t_hibernate_order_item
8. select * from t_hibernate_order_item
最终得到了一个List<OrderItem> orderItems
9.给order的关联关系属性赋值
List(Order o:list){
o.setOrderItems(orderItems);
}