标签:
1、类Role 和Function类 Fole: public class Role { private int id; private String name; private Set<Function> functions = new HashSet<Function>(0); //get…set } Function: public class Function { private int id; private String name; private String code; private String url; private Set<Role> roles = new HashSet<Role>(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 <hibernate-mapping package="cn.siggy.pojo"> <class name="Role"> <id name="id"> <generator class="native"></generator> </id> <property name="name"/> <!-- 多对多 --> <set name="functions" table="role_func" cascade="save-update"> <!-- 表示当前类 映射到关系表中的列--> <key column="rid"/> <!-- 所对应的另一方在关系表中的列 --> <many-to-many column="fid" class="Function"/> </set> </class> </hibernate-mapping> function.hbm.xml <hibernate-mapping package="cn.siggy.pojo"> <class name="Function"> <id name="id"> <!-- foreign表示引用外键 --> <generator class="native"/> </id> <property name="name"/> <property name="code"/> <property name="url"/> <set name="roles" table="role_func" inverse="true"> <key column="fid"/> <many-to-many column="rid" class="Role"/> </set> </class> </hibernate-mapping> 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<Function> 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(); } }
标签:
原文地址:http://blog.csdn.net/liusocg520/article/details/51205594