【问题标题】:JPQL query / JPA / Spring boot best practice of updating many to many tableJPQL 查询/JPA/Spring boot 更新多对多表的最佳实践
【发布时间】:2020-10-02 07:46:51
【问题描述】:

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

用数据更新users_cities 表的最佳做法是什么?我应该删除该特定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;


}

【问题讨论】:

    标签: spring-boot jpa spring-data-jpa jpql


    【解决方案1】:

    我是否应该删除该特定 userId 的所有内容并插入新数组

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

    另外,如何批量删除和分别插入数据,以供多对多参考?

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

    【讨论】:

      猜你喜欢
      • 2020-03-29
      • 2015-08-06
      • 1970-01-01
      • 2019-11-23
      • 2020-03-08
      • 2019-03-25
      • 1970-01-01
      • 2014-10-02
      • 1970-01-01
      相关资源
      最近更新 更多