首页 > 解决方案 > Spring boot JPA - 使用Controller中的额外列更新ManyToMany关系的中间表的最佳解决方案是什么?

问题描述

我在我的项目中使用 Spring Boot 作为后端。在数据库(MySQL)中,我有一个多对多关系,其中包含下一个实体:用户、兴趣和 relUserInterest。RelUserInterest 是 User 和 Interest 之间的中间表,并且有额外的列。

用户实体

@Entity
public class User {

    @Id @GeneratedValue private Long id;
     
    @NotNull
    @Column (unique = true) private String email;

    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
    @NotNull
    Set<RelUserInterest> priority = new HashSet<>();

    // more attributes, constructor, get and set
}

利益实体

@Entity
public class Interest {
    @Id
    @GeneratedValue
    private long id;

    @NotEmpty
    @Column(unique = true)
    private String nameInterest;

    @OneToMany(mappedBy = "interest", cascade = CascadeType.ALL)
    @NotNull
    Set<RelUserInterest> priority = new HashSet<>();

    // more attributes, constructor, get and set
}

RelUserInterest 实体

@Entity
@Table(name = "rel_user_interest")
@IdClass(UserInterestId.class)
public class RelUserInterest implements Serializable {

    @Id
    @ManyToOne
    @JoinColumn(name = "user_id", referencedColumnName = "id")
    User user;

    @Id
    @ManyToOne
    @JoinColumn(name = "interest_id", referencedColumnName = "id")
    Interest interest;

    int priority;

    //  constructor, get and set
}

到目前为止,一切都很好。我想更新用户和他们的兴趣。我的控制器是这个。我想做的是当我更新现有用户时,更新中间表(RelUserInterest)。

@PutMapping("/update/{id}")
    public ResponseEntity<?> updateUser(@Validated @RequestBody UserDTOUpdate userDTOUpdate, BindingResult result, @PathVariable Long id) {
        // More code
        User user = usersService.getUserById(id);
        
        // Code updating other attributes

        // Here this the problem --> I don't know how to update the attribute priority of RelUserInterest

        usersService.updateUser(user);
        return new ResponseEntity<>(new Mensaje("Usuario actualizado"), HttpStatus.CREATED);
    }

我找到了几个链接,但我不确定哪个是最好的解决方案,我不知道如何使用我的代码。

在邮递员中,我想发送下一个 JSON,尽管如果解决方案有必要,兴趣数组可能会有所不同:

{
    "age": 22,
    "genre": "Male",
    "userName": "Miguel",
    "roles": [
        "ROLE_ADMIN",
        "ROLE_USER"
    ],
    "interest": [
        {
            "interestID": 1,
            "nameInterest": "Museum",
            "priority": 9
        }
    ]
}

问题

那么,问题来了:如何更新 RelUserEntity 表的属性优先级?我认为制作中间表存储库是一个错误。我有点失落。我希望你能帮助我。谢谢你。

标签: spring-bootjpaspring-data-jpaspring-datamany-to-many

解决方案


推荐阅读