JPQL查询/ JPA / Spring Boot更新多对多表的最佳实践

问题描述 投票:0回答:1

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

用数据更新users_cities表的最佳实践是什么?我应该只删除该特定userId的所有内容并插入新数组还是...?〜

此外,如何delete并分别insert批量存储数据,以供多对多参考?!

@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;


}
spring-boot jpa spring-data-jpa jpql
1个回答
0
投票

我应该只删除该特定userId的所有内容并插入新数组吗?>

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

而且,如何进行批量删除和删除以供多对多参考?

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

© www.soinside.com 2019 - 2024. All rights reserved.