gpt4 book ai didi

java - 使用 hibernate 管理多对多关系

转载 作者:行者123 更新时间:2023-12-02 10:33:31 24 4
gpt4 key购买 nike

我正在制作简单的 spring mvc web 应用程序,并且我正在将 hibernate 与 oracle 结合使用。我有两个模型 - 用户和角色,我想定义它们之间的多对多关系。我看过几个教程并定义了我的模型,如下所示:

这是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....
}

这是角色类:

@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

此错误表明该表不存在,所以我感兴趣的是我应该手动创建它(我不这么认为)还是我在这里遗漏了任何内容?

最佳答案

只需将@ManyToMany 放在一个地方即可。

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

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

关于java - 使用 hibernate 管理多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53470282/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com