Hibernate5入门(四)映射之自身关联

目录

一、实体类Menu.java

二、映射文件Menu.hbm.xml

三、测试类


 

学习笔记,为了加强记忆和深入理解在此记录备忘。如有错误和理解不当之处,还望指正。万分感谢!

另外,实例和内容有些是参照网络其他博文,如有侵权可联系删掉。


以菜单为例介绍自关联一对多,父菜单对应多个子菜单。

一、实体类Menu.java

package demo.entity;

import java.util.HashSet;
import java.util.Set;

public class Menu {

	private int menuId;
	private String menuName;
	// 菜单和子菜单是一对多,这了引入父类对象
	private Menu parentMenu;
	// 这里引入子类对象集合
	private Set childMenus = new HashSet<>();
	
	public int getMenuId() {
		return menuId;
	}
	public void setMenuId(int menuId) {
		this.menuId = menuId;
	}
	public String getMenuName() {
		return menuName;
	}
	public void setMenuName(String menuName) {
		this.menuName = menuName;
	}
	public Menu getParentMenu() {
		return parentMenu;
	}
	public void setParentMenu(Menu parentMenu) {
		this.parentMenu = parentMenu;
	}
	public Set getChildMenus() {
		return childMenus;
	}
	public void setChildMenus(Set childMenus) {
		this.childMenus = childMenus;
	}
}

二、映射文件Menu.hbm.xml





    
        
            
            
        
        
            
        
          
          
              
              
          
    

三、测试类

package demo.test;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import demo.entity.Menu;

class JunitTest {

	private Configuration configuration = new Configuration().configure();
	private SessionFactory sFactory = configuration.buildSessionFactory();
	private Session session = null;
	private Transaction transaction = null;
	@BeforeEach
	void setUp() throws Exception {
		session = sFactory.openSession();
		transaction = session.beginTransaction();
	}

	@AfterEach
	void tearDown() throws Exception {
		transaction.commit();
		session.close();
	}
	
	@Test
	public void Menutest() {
		
		Menu menu = new Menu();
		menu.setMenuName("根节点");
		
		Menu menu1 = new Menu();
		menu1.setMenuName("一级菜单");
		menu1.setParentMenu(menu);
		
		Menu childMenu1 = new Menu();
		childMenu1.setMenuName("一级菜单1子菜单1");
		childMenu1.setParentMenu(menu1);
		
		Menu childMenu2 = new Menu();
		childMenu2.setMenuName("一级菜单1子菜单2");
		childMenu2.setParentMenu(menu1);
		
		session.save(menu);
		session.save(menu1);
		session.save(childMenu1);
		session.save(childMenu2);
	}
	
	
}

 

你可能感兴趣的:(Hibernate)