我想更新我的应用程序,目前,我有用户和一般类别列表,我想由用户添加一个类别列表,除了管理员用户谁拥有所有类别。所以我想做一个多对多的关系。我发现没有必要制作一个只有id的表。
我使用Spring Boot与JPA和MongoDB作为我的数据库。
\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
}
just need @DBRef