JPQL 查询/JPA/Spring 引导更新多对多的最佳实践table

JPQL query / JPA / Spring boot best practice of updating many to many table

我有一个 user table 和一个 city table 并且我有一个连接 table users_cities(列:id, user_id、city_id)。一个用户可以关注多个城市。 从客户端我发送了一个 cityIds 的数组。有些可能是新的,有些可能仍处于选中状态,有些可能已被取消选择。

用数据更新 users_cities table 的最佳做法是什么?我应该只删除那个特定 userId 的所有内容并插入新数组还是...?~

此外,一个 deleteinsert 如何批量处理数据,供多对多参考?!

@Getter
@Setter
@NoArgsConstructor
@ToString
@Accessors(chain = true)
@Entity
@Table(name = "users")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(unique = true)
    private String email;

    private String password;

    private Boolean isGuest;

    @ManyToMany(fetch = FetchType.EAGER)
    private Set<Role> roles;

    @ManyToOne()
    @JoinColumn(name = "country_following_id")
    private Country countryFollowing;

    @ManyToMany()
    private Set<City> citiesFollowing;

    @ManyToMany()
    private Set<Offer> offersFollowing;

}

@Getter
@Setter
@NoArgsConstructor
@ToString
@Accessors(chain = true)
@Entity
@Table(name = "cities")
public class City {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @NonNull
    private Long id;

    private String countryCode;
    private String name;

    @Latitude
    private Double latitude;
    @Longitude
    private Double longitude;


}

Should I just delete everything for that particular userId and insert the new array

既然连接用户和城市的关系没有自己的身份,这听起来很合理

Also, how does one delete and repsectively insert the data in bulk, for a many to many reference?

只需清除 User.citiesFollowing 集合并重新填充它(提示:由于您已准备好 cityIds,您可以使用 EntityManager.getReference() 加载城市)