一、一对多的关联配置
1、关联指的是类之间的引用关系。
如果类A与类B关联,那么被引用的类B将被定义为类A的属性。
2、一对多的关联:
例如:订单和订单项,一个订单有多个订单项;
但是一个订单项只有一个订单;
3、创建实体类和映射文件
①、实体类:
(1)Order
package com.ysq.two.entity;
import java.util.HashSet;
import java.util.Set;
public class Order {
// create table t_hibernate_order
// (
// order_id int primary key auto_increment,
// order_no varchar(50) not null
// );
private Integer orderId;
private String orderNo;
//注意:变量属性一定用接口进行接受
private Set<OrderItem> orderItems = new HashSet<>();
private Integer initOrderItems = 0;//0代表懒加载,1代表强制加载
public Integer getInitOrderItems() {
return initOrderItems;
}
public void setInitOrderItems(Integer initOrderItems) {
this.initOrderItems = initOrderItems;
}
public Set<OrderItem> getOrderItems() {
return orderItems;
}
public void setOrderItems(Set<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;
}
}
(2)OrderItem
package com.ysq.two.entity;
public class OrderItem {
// create table t_hibernate_order_item
// (
// order_item_id int primary key auto_increment,
// product_id int not null,
// quantity int not null,
// oid int not null,
// foreign key(oid) references t_hibernate_order(order_id)
// );
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;
}
}
②、映射文件:
(1)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.ysq.two.entity.Order" table="t_hibernate_order">
<id name="orderId" type="java.lang.Integer" column="order_id">
<generator class="increment"></generator>
</id>
<property name="orderNo" type="java.lang.String" column="order_no"/>
<!--
cascade:级联属性配置
inverse:关联关系交给对方维护吗?
-->
<set name="orderItems" cascade="save-update" inverse="true">
<key column="oid"></key>
<one-to-many class="com.ysq.two.entity.OrderItem"/>
</set>
</class>
</hibernate-mapping>
(2)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.ysq.two.entity.OrderItem" table="t_hibernate_order_item">
<id name="orderItemId" type="java.lang.Integer" column="order_item_id">
<generator class="increment"></generator>
</id>
<property name="productId" type="java.lang.Integer" column="product_id"/>
<property name="quantity" type="java.lang.Integer" column="quantity"/>
<property name="oid" type="java.lang.Integer" column="oid"/>
<!-- Repeated column in mapping for entity: com.zking.four.entity.OrderItem column: oid (should be mapped with insert="false" update="false") -->
<many-to-one name="order" class="com.ysq.two.entity.Order" insert="false" update="false" column="oid"></many-to-one>
</class>
</hibernate-mapping>
核心配置文件(hibernate.cfg.xml)
<!-- 一对多 -->
<mapping resource="com/ysq/two/entity/Order.hbm.xml" />
<mapping resource="com/ysq/two/entity/OrderItem.hbm.xml" />
工具类:
package com.ysq.two.util;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/**
* 1、用来生产session会话的
* 2、用来测试你的hibernate配置是否正确
* @author Administrator
*
*/
public class SessionFactoryUtil {
static SessionFactory sessionFactory;
static {
Configuration configure = new Configuration().configure("hibernate.cfg.xml");
sessionFactory = configure.buildSessionFactory();
}
public static Session getSession() {
Session session = sessionFactory.getCurrentSession();
if(session == null) {
session = sessionFactory.openSession();
}
return session;
}
public static void main(String[] args) {
Session session = SessionFactoryUtil.getSession();
// Calling method 'isConnected' is not valid without an active transaction (Current status: NOT_ACTIVE)
session.beginTransaction();
System.out.println(session.isConnected());
session.close();
System.out.println(session.isConnected());
}
}
4、dao层
①、OrderDao
package com.ysq.two.dao;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.ysq.two.entity.Order;
import com.ysq.two.entity.OrderItem;
import com.ysq.two.util.SessionFactoryUtil;
public class OrderDao {
public Order get(Order order) {
Session session = SessionFactoryUtil.getSession();
Transaction transaction = session.beginTransaction();
Order o = session.get(Order.class, order.getOrderId());
// 并且想要查询出关联的订单项的数据是,采用强制加载
if(o != null && new Integer(1).equals(order.getInitOrderItems())) {
// 强制加载订单o关联的订单项数据
Hibernate.initialize(o.getOrderItems());
}
transaction.commit();
session.close();
return o;
}
public List<Order> list() {
Session session = SessionFactoryUtil.getSession();
Transaction transaction = session.beginTransaction();
List<Order> list = session.createQuery("from Order").list();
for (Order o: list) {
Hibernate.initialize(o.getOrderItems());
}
transaction.commit();
session.close();
return list;
}
public void delete(Order order) {
Session session = SessionFactoryUtil.getSession();
Transaction transaction = session.beginTransaction();
Order o = session.get(Order.class, order.getOrderId());
for(OrderItem oi:o.getOrderItems()) {
session.delete(oi);
}
session.delete(o);
transaction.commit();
session.close();
}
}
②、OrderItemDao
package com.ysq.two.dao;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.ysq.two.entity.OrderItem;
import com.ysq.two.util.SessionFactoryUtil;
public class OrderItemDao {
public OrderItem get(OrderItem orderItem) {
Session session = SessionFactoryUtil.getSession();
Transaction transaction = session.beginTransaction();
OrderItem oi = session.get(OrderItem.class, orderItem.getOrderItemId());
transaction.commit();
session.close();
return oi;
}
}
5、orderDaoTest
package com.ysq.two.dao;
import java.util.List;
import org.junit.Test;
import com.ysq.two.entity.Order;
public class OrderDaoTest {
private OrderDao orderDao = new OrderDao();
/**
* org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.ysq.two.entity.Order.orderItems, could not initialize proxy - no Session
* 1.正常查询
* 2.懒加载异常错误
* 3.性能调优(解释了hibernate默认懒加载的原因)
*
* 实际场景:
* 1.只使用订单表的数据
* 希望懒加载
* 2.需要同时使用订单表以及订单项表数据
* 不希望懒加载
*/
@Test
public void testGet() {
Order order = new Order();
order.setOrderId(7);
// order.setInitOrderItems(1);
Order o = this.orderDao.get(order);
System.out.println(o.getOrderNo());
// System.out.println(o.getOrderItems());
}
@Test
public void testList() {
List<Order> list = this.orderDao.list();
for (Order o : list) {
System.out.println(o.getOrderNo());
// System.out.println(o.getOrderItems().size());
}
}
@Test
public void testDelete() {
Order order = new Order();
order.setOrderId(6);
this.orderDao.delete(order);
}
}
6、测试
①、运行testGet拿到对应的订单
@Test
public void testGet() {
Order order = new Order();
order.setOrderId(7);
Order o = this.orderDao.get(order);
System.out.println(o.getOrderNo());
}
运行结果:
查询到为7的订单
②、运行testGet拿到订单对应的订单项
@Test
public void testGet() {
Order order = new Order();
order.setOrderId(7);
Order o = this.orderDao.get(order);
System.out.println(o.getOrderNo());
System.out.println(o.getOrderItems());
}
运行结果:
报错原因:默认使用懒加载,在执行完上面那个输出时就已经关闭session了,所以会报错
解决方法:
强制加载
@Test
public void testGet() {
Order order = new Order();
order.setOrderId(7);
order.setInitOrderItems(1);
Order o = this.orderDao.get(order);
System.out.println(o.getOrderNo());
System.out.println(o.getOrderItems());
}
运行结果:
性能调优(解释了hibernate默认采用懒加载的原因):
1、只需要订单表的数据时,同时会将订单项表的数据查询出来,用到的sql语句量庞大;
2、通过字段控制,所以默认为懒加载为0,需要订单项时将order实体类的initOrderItems字段改为1强制加载即可。
二、一对多的自关联
分析(模拟环境:树形菜单):
一对多的自关联是指自己可以有多个子节点,但父节点只有一个,并且是在自己本身的表里
1、实体类(TreeNode)映射文件(TreeNode.hbm.xml)
①、TreeNode
唯一没有描述的parent_node_id,因为parent_node_id关联当前节点与父节点的关联属性;
package com.ysq.two.entity;
import java.util.HashSet;
import java.util.Set;
/**
* 将order与orderitem的关系描述到一个类中
* @author zjjt
*
*/
public class TreeNode {
private Integer nodeId;
private String nodeName;
private Integer treeNodeType;
private Integer position;
private String url;
private TreeNode parent;
private Set<TreeNode> children = new HashSet<TreeNode>();
private Integer initChildren = 0;
public Integer getNodeId() {
return nodeId;
}
public void setNodeId(Integer nodeId) {
this.nodeId = nodeId;
}
public String getNodeName() {
return nodeName;
}
public void setNodeName(String nodeName) {
this.nodeName = nodeName;
}
public Integer getTreeNodeType() {
return treeNodeType;
}
public void setTreeNodeType(Integer treeNodeType) {
this.treeNodeType = treeNodeType;
}
public Integer getPosition() {
return position;
}
public void setPosition(Integer position) {
this.position = position;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public TreeNode getParent() {
return parent;
}
public void setParent(TreeNode parent) {
this.parent = parent;
}
public Set<TreeNode> getChildren() {
return children;
}
public void setChildren(Set<TreeNode> children) {
this.children = children;
}
public Integer getInitChildren() {
return initChildren;
}
public void setInitChildren(Integer initChildren) {
this.initChildren = initChildren;
}
// @Override
// public String toString() {
// return "TreeNode [nodeId=" + nodeId + ", nodeName=" + nodeName + ", treeNodeType=" + treeNodeType
// + ", position=" + position + ", url=" + url + ", children=" + children + "]";
// }
@Override
public String toString() {
return "TreeNode [nodeId=" + nodeId + ", nodeName=" + nodeName + ", treeNodeType=" + treeNodeType
+ ", position=" + position + ", url=" + url + "]";
}
}
②、映射文件
TreeNode.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.ysq.two.entity.TreeNode" table="t_hibernate_sys_tree_node">
<id name="nodeId" type="java.lang.Integer" column="tree_node_id">
<generator class="increment" />
</id>
<property name="nodeName" type="java.lang.String"
column="tree_node_name">
</property>
<property name="treeNodeType" type="java.lang.Integer"
column="tree_node_type">
</property>
<property name="position" type="java.lang.Integer"
column="position">
</property>
<property name="url" type="java.lang.String"
column="url">
</property>
<many-to-one name="parent" class="com.ysq.two.entity.TreeNode" column="parent_node_id"/>
<set name="children" cascade="save-update" inverse="true">
<key column="parent_node_id"></key>
<one-to-many class="com.ysq.two.entity.TreeNode"/>
</set>
</class>
</hibernate-mapping>
3、dao层、配置、测试
①、TreeNodeDao
package com.ysq.two.dao;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.ysq.two.entity.TreeNode;
import com.ysq.two.util.SessionFactoryUtil;
public class TreeNodeDao {
public TreeNode load(TreeNode treeNode) {
Session session = SessionFactoryUtil.getSession();
Transaction transaction = session.beginTransaction();
TreeNode t = session.load(TreeNode.class, treeNode.getNodeId());
if(t != null && new Integer(1).equals(treeNode.getInitChildren())) {
Hibernate.initialize(t.getChildren());
Hibernate.initialize(t.getParent());
}
transaction.commit();
session.close();
return t;
}
}
②、核心配置文件(hibernate.cfg.xml)
<!-- 一对多的自关联 -->
<mapping resource="com/ysq/two/entity/TreeNode.hbm.xml" />
③、TreeNodeDaoTest
package com.ysq.two.dao;
import org.junit.Test;
import com.ysq.two.entity.TreeNode;
public class TreeNodeDaoTest {
private TreeNodeDao treeNodeDao = new TreeNodeDao();
// @Before
// public void setUp() throws Exception {
// }
//
// @After
// public void tearDown() throws Exception {
// }
@Test
public void testLoad() {
TreeNode treeNode = new TreeNode();
treeNode.setNodeId(6);
treeNode.setInitChildren(1);
TreeNode t = this.treeNodeDao.load(treeNode);
System.out.println(t);
System.out.println(t.getParent());
System.out.println(t.getChildren());
}
}
运行结果:
三、多对多的关联
理解:把它想成两个一对多,中间表里有两个表的外键,两个表分别与中间表都是一个一对多;
例如:书籍和书籍类别表,一个书籍多个类别,一个类别多本书籍;
1、实体类、映射文件
①、书籍
(1)、Book .
package com.ysq.two.entity;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
public class Book implements Serializable{
// book_id int primary key auto_increment,
// book_name varchar(50) not null,
// price float not null
private Integer bookId;
private String bookName;
private Float price;
private Set<Category> categories = new HashSet<Category>();
private Integer initCategories = 0;
public Integer getInitCategories() {
return initCategories;
}
public void setInitCategories(Integer initCategories) {
this.initCategories = initCategories;
}
public Integer getBookId() {
return bookId;
}
public void setBookId(Integer bookId) {
this.bookId = bookId;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public Float getPrice() {
return price;
}
public void setPrice(Float price) {
this.price = price;
}
public Set<Category> getCategories() {
return categories;
}
public void setCategories(Set<Category> categories) {
this.categories = categories;
}
@Override
public String toString() {
return "Book [bookId=" + bookId + ", bookName=" + bookName + ", price=" + price + "]";
}
public Book(Integer bookId, String bookName) {
super();
this.bookId = bookId;
this.bookName = bookName;
}
public Book() {
super();
}
}
(2)、映射文件
book.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.ysq.two.entity.Book" table="t_hibernate_book">
<!-- <cache usage="read-only" region="com.ysq.two.entity.Book"/> -->
<id name="bookId" type="java.lang.Integer" column="book_id">
<generator class="increment" />
</id>
<property name="bookName" type="java.lang.String"
column="book_name">
</property>
<property name="price" type="java.lang.Float"
column="price">
</property>
<!-- table:中间表
name:关联属性
inverse:反转
key:当前表的主键在中间表的外键
many-to-many:当前表的主键在中间表查出另一张表的外键
-->
<set table="t_hibernate_book_category" name="categories" cascade="save-update" inverse="true">
<!-- one -->
<key column="bid"></key>
<!-- many -->
<many-to-many column="cid" class="com.ysq.two.entity.Category"></many-to-many>
</set>
</class>
</hibernate-mapping>
②、书籍类别
(1)、Category
package com.ysq.two.entity;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
public class Category implements Serializable{
// category_id int primary key auto_increment,
// category_name varchar(50) not null
private Integer categoryId;
private String categoryName;
private Set<Book> books = new HashSet<Book>();
public Integer getCategoryId() {
return categoryId;
}
public void setCategoryId(Integer categoryId) {
this.categoryId = categoryId;
}
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
public Set<Book> getBooks() {
return books;
}
public void setBooks(Set<Book> books) {
this.books = books;
}
@Override
public String toString() {
return "Category [categoryId=" + categoryId + ", categoryName=" + categoryName + "]";
}
}
(2)、映射文件
category.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.ysq.two.entity.Category" table="t_hibernate_category">
<id name="categoryId" type="java.lang.Integer" column="category_id">
<generator class="increment" />
</id>
<property name="categoryName" type="java.lang.String"
column="category_name">
</property>
<set table="t_hibernate_book_category" name="books" cascade="save-update" inverse="true">
<key column="cid"></key>
<many-to-many column="bid" class="com.ysq.two.entity.Book"></many-to-many>
</set>
</class>
</hibernate-mapping>
核心配置文件(hibernate.cfg.xml)
<!-- 多对多 -->
<mapping resource="com/ysq/two/entity/Category.hbm.xml" />
<mapping resource="com/ysq/two/entity/Book.hbm.xml" />
2、dao方法
BookDao
package com.ysq.two.dao;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.ysq.two.entity.Book;
import com.ysq.two.entity.Category;
import com.ysq.two.util.SessionFactoryUtil;
public class BookDao /*extends BaseDao*/{
public Integer addBook(Book book) {
Session session = SessionFactoryUtil.getSession();
Transaction transaction = session.beginTransaction();
Integer bid = (Integer) session.save(book);
transaction.commit();
session.close();
return bid;
}
public Integer addCategory(Category category) {
Session session = SessionFactoryUtil.getSession();
Transaction transaction = session.beginTransaction();
Integer cid = (Integer) session.save(category);
transaction.commit();
session.close();
return cid;
}
public Category getCategory(Category category) {
Session session = SessionFactoryUtil.getSession();
Transaction transaction = session.beginTransaction();
Category c = session.get(Category.class, category.getCategoryId());
transaction.commit();
session.close();
return c;
}
public Book getBook(Book book) {
Session session = SessionFactoryUtil.getSession();
Transaction transaction = session.beginTransaction();
Book b = session.get(Book.class, book.getBookId());
if (b != null && new Integer(1).equals(book.getInitCategories())) {
Hibernate.initialize(b.getCategories());
}
transaction.commit();
session.close();
return b;
}
public void delBook(Book book) {
Session session = SessionFactoryUtil.getSession();
Transaction transaction = session.beginTransaction();
session.delete(book);
transaction.commit();
session.close();
}
public void delCategory(Category category) {
Session session = SessionFactoryUtil.getSession();
Transaction transaction = session.beginTransaction();
Category c = session.get(Category.class, category.getCategoryId());
if(c!=null) {
for (Book b : c.getBooks()) {
// 通过在被控方通过主控方来解除关联关系,最后被控方再做删除
b.getCategories().remove(c);
}
}
session.delete(c);
transaction.commit();
session.close();
}
}
TreeNodeDaoTest
package com.ysq.two.dao;
import org.junit.Test;
import com.ysq.two.entity.Book;
import com.ysq.two.entity.Category;
public class BookDaoTest {
private BookDao bookDao = new BookDao();
@Test
public void testGetBook() {
Book book = new Book();
book.setBookId(8);
book.setInitCategories(1);
Book b = this.bookDao.getBook(book );
System.out.println(b.getBookName());
System.out.println(b.getCategories());
}
/**
* book.hbm.xml inverse=fasle
* category.hbm.xml inverse=true
* 数据添加正常
* 书籍表、桥接表各新增一条数据
*/
@Test
public void test1() {
Book book = new Book();
book.setBookName("孙硅的龟生");
book.setPrice(10f);
Category category = new Category();
category.setCategoryId(13);
// 直接将category对象加入到新建的book中是错误的,因为此时的category是临时态的,hibernate是不会管理的
// book.getCategories().add(category);
Category c = this.bookDao.getCategory(category);
// c.getBooks().add(book);
book.getCategories().add(c);
this.bookDao.addBook(book);
}
/**
* book.hbm.xml inverse=true
* category.hbm.xml inverse=true
* 只增加书籍表数据
* 桥接表不加数据
* 原因:双方都没有去维护关系
*/
@Test
public void test2() {
Book book = new Book();
book.setBookName("小白自传");
book.setPrice(10f);
Category category = new Category();
category.setCategoryId(5);
Category c = this.bookDao.getCategory(category);
book.getCategories().add(c);
this.bookDao.addBook(book);
// c.getBooks().add(book);
}
}
3、测试
①、拿到ID为8的书籍和书籍类别
@Test
public void testGetBook() {
Book book = new Book();
book.setBookId(8);
book.setInitCategories(1);
Book b = this.bookDao.getBook(book );
System.out.println(b.getBookName());
System.out.println(b.getCategories());
}
运行结果:
②、一正一反
/**
* book.hbm.xml inverse=true
* category.hbm.xml inverse=false
* 数据添加正常
* 书籍表、桥接表各新增一条数据
*/
@Test
public void test1() {
Book book = new Book();
book.setBookName("孙硅的龟生");
book.setPrice(10f);
Category category = new Category();
category.setCategoryId(13);
// 直接将category对象加入到新建的book中是错误的,因为此时的category是临时态的,hibernate是不会管理的
// book.getCategories().add(category);
Category c = this.bookDao.getCategory(category);
// c.getBooks().add(book);
book.getCategories().add(c);
this.bookDao.addBook(book);
}
运行结果:
book表:
category表:
③、两边都为true
**
* book.hbm.xml inverse=true
* category.hbm.xml inverse=true
* 只增加书籍表数据
* 桥接表不加数据
* 原因:双方都没有去维护关系
*/
@Test
public void test2() {
Book book = new Book();
book.setBookName("小白自传");
book.setPrice(10f);
Category category = new Category();
category.setCategoryId(5);
Category c = this.bookDao.getCategory(category);
book.getCategories().add(c);
this.bookDao.addBook(book);
// c.getBooks().add(book);
}
运行结果:
book表:
category表: