程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> JAVA綜合教程 >> hibernate基於主鍵的雙向多對多的關聯映射

hibernate基於主鍵的雙向多對多的關聯映射

編輯:JAVA綜合教程

hibernate基於主鍵的雙向多對多的關聯映射


1、類Role 和Function類
Fole:
public class Role {
	private int id;
	private String name;
	private Set functions = new HashSet(0);
	//get…set

}

  Function:
  
public class Function {
	private int id;
	private String name;
	private String code;
	private String url;
	private Set roles = new HashSet(0);

	public Function() {
		// TODO Auto-generated constructor stub
	}
	public Function(String name, String code, String url) {
		super();
		this.name = name;
		this.code = code;
		this.url = url;
	}

	//get…set }

2、	映射文件
Role.hbm.xml

	
		
			
		
		
		
		
			
			
			
			
		
	

function.hbm.xml
  

	
		
			
			
		
		
		
		

			
			
		
	

3、	測試代碼
@Test
	public void testSave() throws HibernateException, SerialException, SQLException{
		Session session = null;
		Transaction tx = null;
		try{
			session = HibernateUtil.getSession();
			tx = session.beginTransaction();
			Function f1 = new Function("用戶管理","user_mag","userAction");
			Function f2 = new Function("角色管理","role_mag","roleAction");
			Function f3 = new Function("系統管理","sys_mag","sysAction");
			Function f4 = new Function("權限管理","prev_mag","prevAction");
			Role r1 = new Role();
			r1.setName("admin");
			r1.getFunctions().add(f1);
			r1.getFunctions().add(f2);
			r1.getFunctions().add(f3);
			r1.getFunctions().add(f4);
			Role r2 = new Role();
			r2.setName("vip");
			r2.getFunctions().add(f1);
			r2.getFunctions().add(f2);
			session.save(r1);
			session.save(r2);
			
			tx.commit();
			
		}catch (HibernateException e) {
			if(tx!=null)
				tx.rollback();
			e.printStackTrace();
			throw e;
		}finally{
			HibernateUtil.closeSession();
		}
	}
	@Test
	public void testGet(){
		Session session = null;
		Transaction tx = null;
		try{
			session = HibernateUtil.getSession();
			tx = session.beginTransaction();
			Role role = (Role)session.get(Role.class, 1);
			System.out.println("角色名:"+role.getName());
			System.out.println("該角色所對應的權限:");
			for(Iterator iter = role.getFunctions().iterator();
					iter.hasNext();){
				Function func = iter.next();
				System.out.println(func.getName()+"---"+func.getCode());
			}
			//取數據
			tx.commit();
		}catch (HibernateException e) {
			if(tx!=null)
				tx.rollback();
			e.printStackTrace();
			throw e;
		}finally{
			HibernateUtil.closeSession();
		}
	}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved