hibernate关联

目标

一、理解一对多的关联

二、理解懒加载与强制加载

三、理解一对多的自关联

四、理解多对多的关联

一、一对多的关联与懒加载、强制加载

 实体类Order

package com.lxy.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;
	}
	
}

对于一个班级来说,一个班有多个老师,所以order实体类中包含多个老师项集合的属性

OrderItem

package com.lxy.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;
	}
	
}

配置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.lxy.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.lxy.entity.OrderItem"/>
	</set>
</class>
</hibernate-mapping>

 <one-to-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.lxy.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.lxy.entity.Order" insert="false" update="false" column="oid"></many-to-one>
	
</class>
</hibernate-mapping>

二、懒加载

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())) {
			Hibernate.initialize(o.getOrderItems());
		}
		
		transaction.commit();
		session.close();
		return o;
	}

OrderItemDao

package com.lxy.two.dao;
 
import org.hibernate.Session;
import org.hibernate.Transaction;
 
import com.lxy.two.entity.OrderItem;
import com.lxy.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;
	}
}

 hibernate关联

 

orderDaoTest调用查询方法

package com.lxy.two.dao;
 
import java.util.List;
import org.junit.Test;
import com.lxy.two.entity.Order;
 
 
public class OrderDaoTest {
	private OrderDao orderDao = new OrderDao();
 
	/**
	 * org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.zking.two.entity.Order.orderItems, could not initialize proxy - no Session
	 * 1.正常查询
	 * 2.懒加载异常错误
	 * 3.性能调优
	 */
	@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);
	}
 
}

当放开输出查询订单详情时运行,就会报错

hibernate关联

hibernate关联

 报错原因是因为懒加载在执行完上面那个输出时就已经关闭session了,所以会报错

解决:把order.setInitOrderItem(1)放开,把上面实体类的属性设为1

hibernate关联

 当为1的时候就会进if判断,然后将懒加载变成强制加载

hibernate关联

 三、一对多的自关联

Tree Node

package com.lxy.two.entity;
 
import java.util.HashSet;
import java.util.Set;
 
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 + "]";
	}
	
 
}

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.lxy.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.lxy.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.lxy.two.entity.TreeNode"/>
		</set>
	</class>
</hibernate-mapping>

 TreeNodeDao

package com.lxy.two.dao;
 
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;
 
import com.lxy.two.entity.TreeNode;
import com.lxy.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关联

 四、多对多的配置

Book

package com.lxy.two.entity;
 
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
 
public class Book implements Serializable{
    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();
	}
	
	
}

Category

package com.lxy.two.entity;
 
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
 
public class Category implements Serializable{
	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 + "]";
	}
	
}

BookDao

package com.lxy.two.dao;
 
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;
 
import com.lxy.two.entity.Book;
import com.lxy.two.entity.Category;
import com.lxy.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();
	}
	
	
	/*
	 * hql讲解用到(需要继承BaseDao)
	 */
	/**
	 * 没有使用BaseDao之前的代码
	 * @param book
	 * @param pageBean
	 * @return
	 */
//	public List<Book> list(Book book, PageBean pageBean) {
//		Session session = SessionFactoryUtil.getSession();
//		Transaction transaction = session.beginTransaction();
//		String hql = "from Book where 1 = 1";
//
//		if (StringUtils.isNotBlank(book.getBookName())) {
//			hql += " and bookName like :bookName";
//		}
//
//		Query query = session.createQuery(hql);
//		
//		if (StringUtils.isNotBlank(book.getBookName())) {
//			query.setParameter("bookName", book.getBookName());
//		}
//
//		if (pageBean != null && pageBean.isPagination()) {
//			query.setFirstResult(pageBean.getStartIndex());
//			query.setMaxResults(pageBean.getRows());
//		}
//		List<Book> list = query.list();
//		transaction.commit();
//		session.close();
//		return list;
//
//	}
	
	/**
	 * 使用BaseDao之后的代码
	 * @param book
	 * @param pageBean
	 * @return
	 */
//	public List<Book> list2(Book book, PageBean pageBean) {
//		Session session = SessionFactoryUtil.getSession();
//		Transaction transaction = session.beginTransaction();
//		String hql = "from Book where 1 = 1";
//		Map<String, Object> map = new HashMap<String, Object>();
//
//		if (StringUtils.isNotBlank(book.getBookName())) {
//			hql += " and bookName like :bookName";
//			map.put("bookName", book.getBookName());
//		}
//		List list = super.executeQuery(session, hql, map, pageBean);
//		transaction.commit();
//		session.close();
//		return list;
//	}
	
	/**
	 * 使用原生SQL
	 * @param book
	 * @param pageBean
	 * @return
	 */
//	public List list3(Book book, PageBean pageBean) {
		String sql = "select b.*,o.* from t_hibernate_book b,t_hibernate_Order o";
//		String sql = "select * from t_hibernate_book";
//		Session session = SessionFactoryUtil.getSession();
//		Transaction transaction = session.beginTransaction();
//		List list = session.createSQLQuery(sql).list();
//		transaction.commit();
//		session.close();
//		return list;
//	}
}

hibernate关联

 

上一篇:来说说JPA、Hibernate、Spring Data JPA之间的什么关系?


下一篇:Mybatis系列-1-简介