SATURN  RING  STATION

At a distant space view post, we chat about codes.

Hibernate Many-to-Many mapping extra Link Tables problem

 

When I was trying to get a nice database schema for my project Humble Bundle, I discovered a problem. I have two link tables for the relationship between Role and User(red cycles on image).

These were my annotation settings.

public class Role extends AbstartDomainClass{

    @ManyToMany
    @JoinTable
    private List<User> users = new ArrayList<>();
public class User extends AbstartDomainClass{

    @ManyToMany
    @JoinTable
    private List<Role> roles = new ArrayList<>();

 

Although it works, it causes confusion and unnecessary duplication in the database.

Yes, my fault earlier. It’s my ERM, and I did all the Hibernate annotations that generated this database for the project. Enough with excusing, let’s keep going.

Pick up the bible of Hibernate: Java Persistence with Hibernate, find the pages for many-to-many mapping , start a good read, write codes, do testing, and here it is.

 

public class Role extends AbstartDomainClass{

    @ManyToMany
    @JoinTable(
            name = "ROLE_USER",
            joinColumns = @JoinColumn(name = "ROLE_ID"),
            inverseJoinColumns = @JoinColumn(name = "USER_ID")
    )
    private List<User> users = new ArrayList<>();
public class User extends AbstartDomainClass {

    @ManyToMany(mappedBy = "users", fetch = FetchType.EAGER)
    private List<Role> roles = new ArrayList<>();

 

I dropped the whole database and recreate it with already written bootstrap codes.

 

Now the extra link table is gone and looks good.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Hibernate Many-to-Many mapping extra Link Tables problem