- 什么是关联(association)
1.1 关联指的是类之间的引用关系。如果类A与类B关联,那么被引用的类B将被定义为类A的属性。例如:
t_hibernate_order
t_hibernate_order_item
一个订单对应多个订单项class Order{ private List<OrderItem> orderItems; } class OrderItem{ private Order order; } class B{ private String name; } public class A{ private B b = new B; public A(){} }
关联的分类:
关联可以分为一对一、一对多/多对一、多对多关联
订单实体类:
package com.zking.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 + "]";
}
}
订单对应的映射文件
订单项的实体类
package com.zking.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=" + order + "]";
}
}
订单项对应的映射文件
配置一对多文件(hibernate.cgf.xml)
测试:
在orderItem.hbm.xml中添加
作用:放弃对属性的列段进行维护
package com.zking.three.dao;
import static org.junit.Assert.*;
import org.junit.Test;
import com.zking.three.entity.Order;
import com.zking.three.entity.OrderItem;
public class DemoDaoTest {
private DemoDao d=new DemoDao();
@Test
public void testAddOrder() {
Order o=new Order();
o.setOrderNo("橙橙最美");
for (int i = 0; i < 5; i++) {
OrderItem oi=new OrderItem();
oi.setProductId(10+i);
oi.setQuantity(20+i);
o.getOrderItems().add(oi);
}
d.addOrder(o);
}
@Test
public void testAddOrderItem() {
}
@Test
public void testGetOrder() {
}
@Test
public void testGetOrderList() {
}
@Test
public void testDelOrder() {
}
}
成功添加数据
懶加載
第一种:(不推荐)
导致性能变差
添加一行Hibernate.initialize(o.getOrderItems());
就能实现懒加载