In a many-to-many relationship, the intermediate table T_user_role cannot add additional content, such as; creation time, modification time, operator staff, etc.
We can solve this problem in a different way.
Let's start with a class diagram,
Figure 1: User and role relationships
From Figure 1, we find that:
The user class is a one-to-many relationship with the Userrole class.
Role classes and userrole are also a one-to-many relationship
With the Userrole class, we can get a many-to-many relationship between the user class and the role class
Crud:
Userrole
Package Com.demo.model;import java.util.set;/** User Role Relationship * @author Wobendiankun * 2014-11-6 pm 10:33:34 */public class userrole {private int userroleid;private String operator;private User user;private Role role;public userrole () {}public Us Errole (String operator) {this.operator = operator;} Public User GetUser () {return user;} public void SetUser (user user) {this.user = user;} Public role Getrole () {return role;} public void Setrole (role role) {this.role = role;} Public String Getoperator () {return operator;} public void Setoperator (String operator) {this.operator = operator;} public int Getuserroleid () {return userroleid;} public void Setuserroleid (int userroleid) {This.userroleid = Userroleid;}}
Configuration
<?xml version= "1.0"? ><! DOCTYPE hibernate-mapping public "-//hibernate/hibernate mapping DTD 3.0//en" "http// Hibernate.sourceforge.net/hibernate-mapping-3.0.dtd ">
Add
Package Com.demo.model;import Org.hibernate.session;import Org.junit.test;import com.demo.util.hibernateutil;/** Many-to-many variants * @author Wobendiankun * 2014-11-6 pm 10:42:34 */public class Many2manytranstest {@Testpublic void Addtest () {userrole Userrole1=new userrole ("AA"); Userrole1.setuser (new User); Userrole1.setrole (New Role (3)); Userrole userrole2=new userrole ("BB"); Userrole2.setuser (new User); Userrole2.setrole (New Role (3)); Session session = Null;try {session = Hibernateutil.opensession (); Session.begintransaction (); Session.save (UserRole1) ; Session.save (UserRole2); Session.gettransaction (). commit ();} catch (Exception e) {session.gettransaction (). rollback (); E.printstacktrace ();} finally {hibernateutil.closesession ( session);}}}
Emit sql:
Hibernate:insert into T_user_role (operator, user_id, role_id, user_role_id) VALUES (?,?,?,?) Hibernate:insert into T_user_role (operator, user_id, role_id, user_role_id) VALUES (?,?,?,?)
12.many2many Deformation of Hibernate