使用休眠管理多对多关系

时间:2018-11-25 17:56:19

标签: java oracle hibernate spring-mvc

我正在制作简单的Spring MVC Web应用程序,并且我在Oracle中使用了Hibernate。我有两个模型-用户和角色,我想定义它们之间的多对多关系。我看过一些教程并定义了我的模型,如下所示:

这是 User 类:

@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....
} 

这是 Role 类:

@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....
}

当我在服务器上运行此应用程序时,出现以下错误:

enter image description here

此错误表明该表不存在,所以我有兴趣手动创建它(我认为不是)还是在这里丢失任何内容?

1 个答案:

答案 0 :(得分:1)

只需将@ManyToMany放在一个位置即可。

请在角色实体中删除@ManyToMany。 您可以检查下面的链接,以便使用oracle数据库处理@ManyToMany。 我希望这会有所帮助:

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