Search code examples
spring-bootjpaspring-data-jpajpql

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


I have a user table and a city table and I have a connecting table users_cities (columns: id, user_id, city_id). A user can follow multiple cities. From the client side i send an array of cityIds. Some might be new some might still be selected and some might have been deselected.

What is a best practice to update the users_cities table with the data? Should I just delete everything for that particular userId and insert the new array or ... ?~

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

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

}

and

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


}

Solution

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

    Since the relation connecting users and cities does not have an identity of its own, that sounds reasonable

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

    Just clear the User.citiesFollowing collection and populate it anew (hint: since you have cityIds at the ready, you can use EntityManager.getReference() to load the cities)