简体   繁体   English

使用休眠管理多对多关系

[英]Managing many to many relationship with hibernate

I am making simple spring mvc web app and I am using hibernate with oracle. 我正在制作简单的Spring MVC Web应用程序,并且在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: 这是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....
} 

This is Role class: 这是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....
}

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. 只需要将@ManyToMany放在一个位置即可。

Please remove @ManyToMany in Role entity. 请在角色实体中删除@ManyToMany。 You can check the link below in order to deal @ManyToMany using oracle database. 您可以检查下面的链接,以便使用oracle数据库处理@ManyToMany。 I hope this is helpful: 我希望这是有帮助的:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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