Hibernate one-way, many-to-many
I recently developed an OA system and used the Hibernate framework. I found that the relationship between permissions and roles is many-to-many. One permission can be assigned to multiple roles, A role has multiple permissions.
There are two types of multi-to-many relationships: one is unidirectional and the other is multidimensional. This problem has made me very hard. It is complicated to simply understand the language, but you may understand the code.
The process of Role authorization is simulated as follows:
1. Hibernate uses Annotation
2. Use Junit for testing.
3. Use Mysql as the background database.
4. Hibernate does not use automatic table creation or reverse engineering.
Process:
1. Create a table:
Data Table Structure:
SQL statement:
Create table role (# role TABLE RoleId int primary key AUTO_INCREMENT, # role ID RoleName VARCHAR (20) not null # role name); create table privilege (# permission TABLE PrivilegeId int primary key, # permission ID PrivilegeName VARCHAR (45) not null # permission TABLE); create table privilege_role (# permission _ Role intermediate TABLE RoleId INT, PrivilegeId INT, primary key (RoleId, PrivilegeId ), CONSTRAINT rule foreign key (RoleId) REFERENCES role (RoleId), CONSTRAINT fk_role_privilege foreign key (PrivilegeId) REFERENCES privilege (PrivilegeId ));
2. hibernate. cfg. xml file:
com.mysql.jdbc.Driver
jdbc:mysql://localhost:3306/hibernate
root
xxxx
org.hibernate.dialect.MySQL5InnoDBDialect
true
3. Compile the entity class:
Role. java:
package org.jian.domain;import java.util.HashSet;import java.util.Set;import javax.persistence.CascadeType;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.FetchType;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.persistence.JoinTable;import javax.persistence.ManyToMany;import javax.persistence.Table;import javax.persistence.JoinColumn;import org.hibernate.annotations.GenericGenerator;@Entity@Table(name = "Role")public class Role {private int roleId;private String roleName;private Set
privileges = new HashSet
();@Id@GenericGenerator(name = "generator", strategy = "increment")@GeneratedValue(generator = "generator")public int getRoleId() {return roleId;}public void setRoleId(int roleId) {this.roleId = roleId;}@Column(name = "roleName")public String getRoleName() {return roleName;}public void setRoleName(String roleName) {this.roleName = roleName;}@ManyToMany(cascade = CascadeType.REFRESH, fetch = FetchType.EAGER)@JoinTable(name = "privilege_role", joinColumns = { @JoinColumn(name = "RoleId") }, inverseJoinColumns = { @JoinColumn(name = "PrivilegeId") })public Set
getPrivileges() {return privileges;}public void setPrivileges(Set
privileges) {this.privileges = privileges;}}
Privilege. java
package org.jian.domain;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.Id;import javax.persistence.Table;@Entity@Table(name="Privilege")public class Privilege {private int privilegeId;private String privilegeName;@Id@Column(name="privilegeId")public int getPrivilegeId() {return privilegeId;}public void setPrivilegeId(int privilegeId) {this.privilegeId = privilegeId;}public String getPrivilegeName() {return privilegeName;}public void setPrivilegeName(String privilegeName) {this.privilegeName = privilegeName;}}
5. Junit testing class:
Package org. jian. domain; import java. util. set; import org. hibernate. session; import org. hibernate. sessionFactory; import org. hibernate. transaction; import org. hibernate. cfg. annotationConfiguration; import org. junit. afterClass; import org. junit. beforeClass; import org. junit. test; public class AuthorizeTest {private static SessionFactory sf; @ BeforeClass public static void beforeClass () {sf = new AnnotationConfiguration (). configure (). buildSessionFactory () ;}@ AfterClass public static void afterClass () {sf. close ();}/*** initialize the system. The permission is inserted into the database during system initialization */@ Testpublic void initTest () {Privilege p1 = new Privilege (); p1.setPrivilegeId (1); p1.setPrivilegeName ("add log"); Privilege p2 = new Privilege (); p2.setPrivilegeId (2); p2.setPrivilegeName ("delete log "); privilege p3 = new Privilege (); p3.setPrivilegeId (3); p3.setPrivilegeName ("Modify log"); Privilege p4 = new Privilege (); p4.setPrivilegeName ("view log "); p4.setPrivilegeId (4); Session session = sf. openSession (); Transaction tx = session. beginTransaction (); session. save (p1); session. save (p2); session. save (p3); session. save (p4); tx. commit (); session. close ();} /*** add role ** to add permissions for the role * We simulate the "add log" and "view log" permissions *, that is, the permissions with ID 1 and 4 */@ Testpublic void authorizeTest () {Role role = new Role (); role. setRoleName ("manager"); Session session = sf. openSession (); Transaction tx = session. beginTransaction (); // load the permission Privilege p1 = (Privilege) session with id 1 and id 4. get (Privilege. class, 1); Privilege p4 = (Privilege) session. get (Privilege. class, 4); // authorize role for the role. getPrivileges (). add (p1); role. getPrivileges (). add (p4); // Save the role session. save (role); tx. commit (); session. close ();}/*** test the permissions of the newly added role */@ Testpublic void checkPrivilegeTest () {Session session = sf. openSession (); Transaction tx = session. beginTransaction (); Role role = (Role) session. get (Role. class, 1); Set
Privaleges = role. getPrivileges (); System. out. println ("role" + role. getRoleName () + "permissions:"); for (Privilege privilege: privaleges) {System. out. println (privilege. getPrivilegeName ();} tx. commit (); session. close ();}}
6. perform the test:
A. Test initTest () and check the green bar.
Console output:
Hibernate: insert into Privilege (privilegeName, privilegeId) values (?, ?)Hibernate: insert into Privilege (privilegeName, privilegeId) values (?, ?)Hibernate: insert into Privilege (privilegeName, privilegeId) values (?, ?)Hibernate: insert into Privilege (privilegeName, privilegeId) values (?, ?)
B. Test authorizeTest () and check the green bar. The operation is successful.
Console output:
Hibernate: select privilege0_.privilegeId as privileg1_1_0_, privilege0_.privilegeName as privileg2_1_0_ from Privilege privilege0_ where privilege0_.privilegeId=?Hibernate: select privilege0_.privilegeId as privileg1_1_0_, privilege0_.privilegeName as privileg2_1_0_ from Privilege privilege0_ where privilege0_.privilegeId=?Hibernate: select max(roleId) from RoleHibernate: insert into Role (roleName, roleId) values (?, ?)Hibernate: insert into privilege_role (RoleId, PrivilegeId) values (?, ?)Hibernate: insert into privilege_role (RoleId, PrivilegeId) values (?, ?)
The last step is to test checkPrivilegeTest () and green bar.
Console output:
Hibernate: select role0 _. roleId as roleId0_1 _, role0 _. roleName as roleName0_1 _, privileges1 _. roleId as RoleId0_3 _, privilege2 _. privilegeId as Privileg2_3 _, privilege2 _. privilegeId as privileg1_1_0 _, privilege2 _. privilegeName as privileg2_1_0 _ from Role role0 _ left outer join privilege_role privileges1 _ on role0 _. roleId = privileges1 _. roleId left outer join Privilege privilege2 _ on privileges1 _. pridevil EgeId = privilege2 _. privilegeId where role0 _. roleId =? Role managers have the following permissions: Add logs to view logs
From the above we can see that the role has been granted permissions for the "manager" role.
View the data table:
Program development.
2. If you select to automatically generate an ID, we may not be able to determine this ID. In this way, the permission ID cannot be used to determine the role's permissions.
There may be a better design than this design, but currently I only find this design is more suitable. It may be because I did not learn well and did not find a better solution. I hope that some experts can point out my mistakes and help me find a better way.