Hibernate关联关系

Hibernate关联关系,第1张

Hibernate关联关系

目录

一、一对多的配置

二、懒加载

三、一对多的自关联

四、多对多的配置


一、一对多的配置:

          一对多的配置就是一个对应多个,例如:在订单表和订单项表中,一个订单有多个订单项,但是一个订单项只对应一个订单。

配置(user.hbm.xml):

实体类:在order中包含了orderitems这个属性,就是实现一对多的路径

package com.zking.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 orderItems = new HashSet<>();
	
	private Integer initOrderItems = 0;//0代表懒加载,1代表强制加载
	
	
	public Integer getInitOrderItems() {
		return initOrderItems;
	}
	public void setInitOrderItems(Integer initOrderItems) {
		this.initOrderItems = initOrderItems;
	}
	public Set getOrderItems() {
		return orderItems;
	}
	public void setOrderItems(Set 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;
	}
	
}

orderItems:

package com.zking.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.定义:懒加载可以这样理解,只加载某一项东西,其他的东西不会加载          2、 *** 作:在我们进行项目的 *** 作时候,就会想到,当自己把订单的id查出来之后,改订单id下面的对应的订单项会不会也同样出来。

OrderItemsDao:

public class OrderDaoTest {
	private OrderDao orderDao = new OrderDao();

	
	@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());
	}
	

会出现的懒加载错误:

代码:

public class OrderDaoTest {
	private OrderDao orderDao = new OrderDao();

	
	@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());
	}
	

错误图示:

解决办法就是强行加载,或者将下面要执行代码注释掉。

三、一对多的自关联         1、定义:一对多的自关联就好比做树形菜单的时候,就会出现一个最大的节点,下面会有很多的子节点。         2、实 *** :

实体类:

package com.zking.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 children = new HashSet();
	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 getChildren() {
		return children;
	}

	public void setChildren(Set 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文件:




	
		
			
		
		
		
		
		
		
		
		
		
		
		
		
		
			
			
		
	

Dao方法:

package com.zking.two.dao;

import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.zking.two.entity.TreeNode;
import com.zking.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;
	}
}

运行结果:

四、多对多的配置

          1、定义:多对多就好比现实生活中,一个班级有很多个老师,而那一个老师不止带一个班级,通俗点讲:多对多的配置就是两个一对多的配置。下面有一张示意图帮助理解:

 

例如T269班有两个老师,一个是胡老师,另一个是丁娜老师,而丁娜老师不止接手了T269班,还有T281、T278班。

          2、实 ***

entity:

package com.zking.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 categories = new HashSet();
	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 getCategories() {
		return categories;
	}

	public void setCategories(Set 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();
	}
	
	
}
package com.zking.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 books = new HashSet();
	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 getBooks() {
		return books;
	}
	public void setBooks(Set books) {
		this.books = books;
	}
	@Override
	public String toString() {
		return "Category [categoryId=" + categoryId + ", categoryName=" + categoryName + "]";
	}
	
}

dao:

package com.zking.two.dao;

import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.zking.two.entity.Book;
import com.zking.two.entity.Category;
import com.zking.two.util.SessionFactoryUtil;


public class BookDao {
	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();
	}
	
	
	
	
//	public List 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 list = query.list();
//		transaction.commit();
//		session.close();
//		return list;
//
//	}
	
	
//	public List list2(Book book, PageBean pageBean) {
//		Session session = SessionFactoryUtil.getSession();
//		Transaction transaction = session.beginTransaction();
//		String hql = "from Book where 1 = 1";
//		Map map = new HashMap();
//
//		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;
//	}
	
	
//	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;
//	}
}

配置:

运行结果:

今天的知识就分享到这了,希望能够帮助到大家。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/4015688.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-10-22
下一篇 2022-10-22

发表评论

登录后才能评论

评论列表(0条)

保存