使用休眠管理多对多关系 [英] Managing many to many relationship with hibernate

查看:66
本文介绍了使用休眠管理多对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作简单的Spring MVC Web应用程序,并且正在将oracle和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:

这是 User 类:

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?

推荐答案

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

Just need to put @ManyToMany in one place only.

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

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

这篇关于使用休眠管理多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆