I. Expression of relationship
1, the expression in the table
2, the expression in the entity
3. The expression in ORM meta-data
Add in User.hbm.xml:
Add in Role.hbm.xml (on the opposite side):
Second, Operation Association properties
1. Save employees and Roles
1 Public classDemo {2 @Test3 //Save employees and Roles4 Public voidfun1 () {5 //1. Get Session6Session session =hibernateutils.opensession ();7 //2. Turn on the transaction8Transaction tx=session.begintransaction ();9 //3. OperationTen //================================= One //1> creation of two user AUser u1=NewUser (); -U1.setuser_name ("Zhang San"); - theUser u2=NewUser (); -U2.setuser_name ("Ann"); - - //2> creation of two role +Role r1=NewRole (); -R1.setrole_name ("President"); + ARole r2=NewRole (); atR2.setrole_name ("Security"); - - //3> User Expression Relationships - u1.getroles (). Add (R1); - u1.getroles (). Add (R2); - in u2.getroles (). Add (R1); - u2.getroles (). Add (R2); to //4> Role Expression Relationships + r1.getusers (). Add (U1); - r1.getusers (). Add (U2); the * r2.getusers (). Add (U1); $ r2.getusers (). Add (U2);Panax Notoginseng - //5> Call the Save method once save the Session.save (U1); + Session.save (U2); A Session.save (R1); the Session.save (R2); + //================================= - //4. Commit a transaction $ tx.commit (); $ //5. Close Resources - session.close (); - } the}
direct execution will give an error, because in many-to-many relationships, be sure to choose one side to abandon the maintenance relationship! (You can choose to remove the four lines of code for the role expression relationship)
2, for Zhang San new role (only need to modify the contents of the step three actions)
1 //1> get Zhang San users2User User = session.Get(User.class,1l);3 //2> Creating a role-PR4Role r=NewRole ();5R.setrole_name ("PR");6 //3> Adding a role to a user7 user.getroles (). Add (R);8 //4> Converting a role to persistent9Session.save (R);
3, for Zhang San to remove a role (also only need to modify the contents of the step three actions)
1 // 1> get Zhang San users 2 User User = session. Get (User. class 1l ); 3 // 2> Get the Role object to manipulate (security) 4 Role r=session. Get (Role. class 2l ); 5 // 3> Removing a role from a user's role collection 6 User.getroles (). Remove (R);
Third, advanced operation
1. Inverse properties
Based on the above Operation 1 save operation, if you do not remove any code, in the configuration file Role.hbm.xml Add the inverse property, and set to True, you can also complete the operation.
2. Cascading properties
Based on the above Operation 2 new operation, you can choose to remove the last save operation, in the profile User.hbm.xml use the Cascade property, save the user while saving the corresponding role.
Hibernate framework Learning (vii)-many-to-many relationships