Hibernate two-way, many-to-many Association ing based on primary keys
1. class Role and Function class 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. Map File Role. hbm. xml
Function. hbm. xml
3. Test code @ Testpublic void testSave () throws HibernateException, SerialException, SQLException {Session session = null; Transaction tx = null; try {session = HibernateUtil. getSession (); tx = session. beginTransaction (); Function f1 = new Function ("User Management", "user_mag", "userAction"); Function f2 = new Function ("role management", "role_mag ", "roleAction"); Function f3 = new Function ("System Management", "sys_mag", "sysAction"); Function f4 = new Function ("permission management", "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 () ;}@ Testpublic 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 name:" + role. getName (); System. out. println ("permissions for this role:"); for (Iterator
Iter = role. getFunctions (). iterator (); iter. hasNext ();) {Function func = iter. next (); System. out. println (func. getName () + "---" + func. getCode ();} // get the data tx. commit ();} catch (HibernateException e) {if (tx! = Null) tx. rollback (); e. printStackTrace (); throw e;} finally {HibernateUtil. closeSession ();}}