java - 如何使用 Java Spring Boot JPA 进行关系多对多
问题描述
我想更新我的应用程序,目前,我有用户和一般类别列表,我想按用户添加类别列表,但拥有所有类别的管理员用户除外。所以我在考虑做一个多对多的关系。我看到没有必要只制作一个 ID 表。
我正在使用带有 JPA 和 MongoDB 的 Spring Boot 作为我的数据库。
\\Models
@Document(collection = "users")
public class AppUser {
@Transient
public static final String SEQUENCE_NAME = "users_sequence";
@Id
private int id;
@NotBlank
@Size(max = 20)
private String username;
@NotBlank
@Size(max = 120)
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private String password;
@DBRef
private AppRole role = new AppRole();
@ManyToMany(mappedBy = "categories")
private List<AppCategory> lstCategory = new ArrayList();
}
@Document(collection = "categories")
public class AppCategory {
@Transient
public static final String SEQUENCE_NAME = "category_sequence";
@Id
private int id;
private String libelle;
}
第三个表版本
public class AppUser {
...
@ManyToMany
@JoinTable(
name = "usersCategories",
joinColumns = @JoinColumn(name = "user"),
inverseJoinColumns = @JoinColumn(name = "Category"))
private List<AppCategory> lstCategorie = new ArrayList<AppCategory>();
...
}
@Document(collection = "usersCategories")
public class AppUserCategory {
@DBRef
private AppUser User = new AppUser();
@DBRef
private AppCategory Category = new AppCategory();
}
解决方案
\\Models
@Document(collection = "users")
public class AppUser {
@Transient
public static final String SEQUENCE_NAME = "users_sequence";
@Id
private int id;
@NotBlank
@Size(max = 20)
private String username;
@NotBlank
@Size(max = 120)
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private String password;
@DBRef
private AppRole role = new AppRole();
@DBRef
private List<AppCategory> lstCategory = new ArrayList();
}
@Document(collection = "categories")
public class AppCategory {
@Transient
public static final String SEQUENCE_NAME = "category_sequence";
@Id
private int id;
private String libelle;
}
//exemple user
{
"_id": 1,
"username": "myusername",
"email": "myusername@gmail.com",
"password": "",
"role": {
"$ref": "role",
"$id": 1
},
"lstCategory": [
{
"$ref": "categories",
"$id": 2
},
{
"$ref": "categories",
"$id": 3
}
只需要@DBRef
推荐阅读
- ios - 反应原生原生模块 RCTBubblingEventBlock 为空
- ruby - 为什么这个“折叠数组”函数返回的元素少于预期?
- c# - 定时器只执行几次
- html - 使用 Bootstrap - 如何使 2 行,每行有两个水平列,具有相同的高度,同时保持响应
- javascript - 如何使用 reactjs 验证对象数组
- javascript - 打开模式时Javascript触发的CSS转换失败
- android - Google Play Billing(测试模式):为什么我的购买会被自动取消
- vba - 我想知道如何使用表单按钮将记录保存到表中并在保存时打开一个新表单
- java - 我正在尝试使用 selenium 在自动化测试下执行我的 maven 项目
- sql - 加入日期相同或过去的第一个 id