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:

  1. Action 1: insert roles
  2. Action 2: insert users and insert user_role
  3. 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:

RESOURCES:

 

Hibernate Many to Many join table

 

GitHub - lvtutorial/springmvc-user-role: Spring mvc use hibernate manytomany to manage user role