Managing many to many relationship with hibernate

2019-08-18 18:07发布

I am making simple spring mvc web app and I am using hibernate with oracle. I have two models - User and role and I want to define many to many relationship between them. I have seen several tutorials and have defined my models as shown below:

This is User class:

@Entity
@Table(name = "AppUser")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "id_sequence")
    @SequenceGenerator(name = "id_sequence", sequenceName = "ID_SEQ")
    @Column(name = "Id")
    private int id;

    @Column(name = "Username")
    private String username;

    @Column(name = "Password")
    private String password;


    @ManyToMany
    (
        fetch = FetchType.LAZY,
        cascade = {
                      CascadeType.PERSIST,
                      CascadeType.MERGE
                  }
    )
    @JoinTable
    (
        name = "user_roles", 
        joinColumns = { @JoinColumn(name = "user_id", referencedColumnName = "id") }, 
        inverseJoinColumns = { @JoinColumn(name = "role_id", referencedColumnName = "id") }
    )
    private Set<Role> roles = new HashSet<Role>(0);

    //getters and setters....
} 

This is Role class:

@Entity
@Table(name = "role")
public class Role {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "id_sequence")
    @SequenceGenerator(name = "id_sequence", sequenceName = "ID_SEQ")
    private int id;

    private String role;

    @ManyToMany
    (
        fetch = FetchType.LAZY, 
        cascade = {
                      CascadeType.PERSIST,
                      CascadeType.MERGE
                  },
        mappedBy = "roles"
    )
    private Set<User> users;

    //getters and setters....
}

When I run this app on server I get the following error:

enter image description here

This error says that table doesn't exist, so I am interested in should I create it manually(I do not think so) or am I missing anything here?

1条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-08-18 18:33

Just need to put @ManyToMany in one place only.

Please remove @ManyToMany in Role entity. You can check the link below in order to deal @ManyToMany using oracle database. I hope this is helpful:

https://gerardnico.com/jpa/many-to-many#oracle_database

查看更多
登录 后发表回答