Java hibernate manytomany to manage user role
Example: one User have many roles and one Role have many users, and now we will have one User_Role table. We will have following situation:
- Action 1: insert roles
- Action 2: insert users and insert user_role
- Action 3: delete users
We can use persistence.xml to set hibernate.hbm2ddl.auto is “create” to auto create 3 tables in database
Table structure for hibernate manytomany
2) Define java entity for 3 tables
Roles.java
Users.java
USER_ROLE entity, we dom’t need to create, so it created in users entity by hibernate.
If use this define then after action 3 –> Hibernate will delete user_role and delete users but no delete roles
If use define above then after action 3 –> Hibernate will delete user, delete user_role and delete roles.
We can apply this way into the spring mvc simple project. This spring project use hibernate to manage users and roles. To run this project on oracle database. we create table and data by run script below:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
--hibernate manytomany to manage user role
-- Create table
create table ROLES
(
ID NUMBER(19) not null,
CODE VARCHAR2(50 CHAR),
NAME VARCHAR2(255 CHAR)
);
-- Create/Recreate primary, unique and foreign key constraints
alter table ROLES add primary key (ID) using index;
-- Create table
create table USERS
(
ID NUMBER(19) not null,
FULLNAME VARCHAR2(255 CHAR),
USERNAME VARCHAR2(50 CHAR)
);
-- Create/Recreate primary, unique and foreign key constraints
alter table USERS add primary key (ID) using index;
-- Create table
create table USER_ROLE
(
USER_ID NUMBER(19) not null,
ROLE_ID NUMBER(19) not null
);
-- Create/Recreate primary, unique and foreign key constraints
alter table USER_ROLE add primary key (USER_ID, ROLE_ID) using index;
alter table USER_ROLE add constraint FKBC16F46AA154824E foreign key (USER_ID) references USERS (ID);
alter table USER_ROLE add constraint FKBC16F46AFBFF2A78 foreign key (ROLE_ID) references ROLES (ID);
insert into roles (ID, CODE, NAME) values (1, 'A01', 'admin');
insert into roles (ID, CODE, NAME) values (2, 'A02', 'user');
commit;
|
RESOURCES:
Hibernate Many to Many join table
GitHub - lvtutorial/springmvc-user-role: Spring mvc use hibernate manytomany to manage user role