首页 > 解决方案 > 如何使用 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();

}

标签: javaspringmongodbspring-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();

    @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


推荐阅读