简体   繁体   中英

Managing many to many relationship with hibernate

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:

在此处输入图片说明

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM