目标:一:一对多的关联与懒加载、强制加载一:理解一对多的关联
二:理解懒加载与强制加载
三:理解一对多的自关联
四:理解多对多的关联
一对多的关联配置(环境:订单(1)与订单详情(多))与懒加载、强制加载二:一对多的自关联需要用的实体类、dao层、xml文件、测试类
实体类(Order/OrderItem)
Order
package com.sg.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 SetorderItems = 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; } } 分析:
Order中必须有该有的表结构
Order中可以有多个订单详情,所以用集合装起来
设个属性0代表懒加载,1代表强制加载
OrderItem
package com.sg.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; } }分析:
表结构
订单详情只对应一个订单
xml文件(Order.hbm.xml/OrderItem.hbm.xml)
Order.hbm.xml
分析:
该标签是一个对应多个 在这就是一个订单对应多个订单详情
OrderItem.hbm.xml
分析:
该标签是多对一 在这意思是多个订单详情对应一个订单
测试类(OrderDaoTest)与dao层(OrderDao/OrderItemDao)
OrderDaoTest
package com.sg.two.dao; import java.util.List; import org.junit.Test; import com.sg.two.entity.Order; 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()); } @Test public void testList() { Listlist = 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); } } OrderDao
package com.sg.two.dao; import java.util.Iterator; import java.util.List; import org.hibernate.Hibernate; import org.hibernate.Session; import org.hibernate.Transaction; import com.sg.two.entity.Order; import com.sg.two.entity.OrderItem; import com.sg.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())) { Hibernate.initialize(o.getOrderItems()); } transaction.commit(); session.close(); return o; } public Listlist() { Session session = SessionFactoryUtil.getSession(); Transaction transaction = session.beginTransaction(); List 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.sg.two.dao; import org.hibernate.Session; import org.hibernate.Transaction; import com.sg.two.entity.OrderItem; import com.sg.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; } }分析(按方法分析):
执行后查询结果
当我放开输出查询订单详情时运行
就会报下面这个错误
原因:懒加载,在执行完上面那个输出时就已经关闭session了,所以会报错
这个时候把order.setInitOrderItems(1)放开 ,这里是把上面实体类那个属性设为1
当为1的时候会进那个if判断然后将懒加载就会变为强制加载
这个时候再来运行就不会报错了
注:为什么会有懒加载,并且是默认使用懒加载?
我们来运行这个方法
可以看到这个方法的for循环中应用的是强制加载
我们执行可以看到Hibernate编译出了大量的select语句
那么当我们的数据库数据非常多的时候这就会占用大量的资源,而且有时候我们只需要用到
订单表的数据,有时候需要订单表和订单详情表的数据,那么使用懒加载就会节约大量的代
码资源,这是性能的一个调优。
三:多对多的关联需要用的实体类、dao层、xml文件、测试类
分析(模拟环境:树形菜单):
一对多的自关联是指自己可以有多个子节点,但父节点只有一个,并且是在自己本身的表里
实体类(TreeNode)
TreeNode
package com.sg.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 Setchildren = 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 + "]"; } } 分析:
表结构
第一个为父节点(父节点只有一个)
第二个为子节点(子节点可能有多个所以用集合包起来)
第三个为懒加载(0为懒加载,1为强制加载)
xml文件(TreeNode.hbm.xml)
分析:
多对一:多个子节点对应一个父节点
标签里面放着一对多标签:一个父节点对应多个子节点 测试类(TreeNodeDaoTest )以及dao层()
测试类(TreeNodeDaoTest )
package com.sg.two.dao; import org.junit.Test; import com.sg.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()); } }dao层(TreeNodeDao )
package com.sg.two.dao; import org.hibernate.Hibernate; import org.hibernate.Session; import org.hibernate.Transaction; import com.sg.two.entity.TreeNode; import com.sg.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; } }分析:
测试类将控制懒加载的方式将其设置为强制加载
结果展示:
需要用的实体类、dao层、xml文件、测试类
分析(模拟环境:老师与其管理的班级):
多对多可以当成是两个一对多来理解
就像上图一样,一个班级可以多个老师进行管理,老师又可以管理多个班级
实体类(Book/Category)
Book
package com.sg.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 Setcategories = 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(); } } Category
package com.sg.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 Setbooks = 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 + "]"; } } 分析:
两个实体类表中除了表结构都有外,也都有set集合包住对方,说明都可以一对多
xml文件(category.hbm.xml/book.hbm.xml)
category.hbm.xml
book.hbm.xml
分析:
table:中间表
name:关联属性
inverse:反转(一边为false一边为true)具体下面分析解释
key:当前表的主键在中间表的外键
many-to-many:当前表的主键在中间表查出另一表的外键dao方法以及测试类
dao方法(BookDao)
package com.sg.two.dao; import org.hibernate.Hibernate; import org.hibernate.Session; import org.hibernate.Transaction; import com.sg.two.entity.Book; import com.sg.two.entity.Category; import com.sg.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 Listlist(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; // } } 测试类(BookDaoTest)
package com.sg.two.dao; import org.junit.Test; import com.sg.two.entity.Book; import com.sg.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()); } @Test public void test1() { Book book = new Book(); book.setBookName("bbbb"); book.setPrice(10f); Category category = new Category(); category.setCategoryId(5); // 直接将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); } @Test public void test2() { Book book = new Book(); book.setBookName("dddd"); 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); } }分析:
解释为什么要一边为false一边为true
一边为false一边为true时
添加”呜呜呜“
数据库:
这边中间表维护了
当都为true时
结果:
书籍表肯定会添加一条数据
但中间表没有维护
拜拜了各位!!!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)