Home > Software design >  How to update a List of Users in the User class Spring Boot
How to update a List of Users in the User class Spring Boot

Time:04-01

I have a Java User class, a user can have friends (List<User>). By default, Hibernate create two tables : USER and USER_FRIENDS(USER_ID,FRIENDS_ID)

The problem is when I change friends in my code and that I save(user), spring add the new friends but don't remove in the database the friends removed from the array list.

@Entitypublic class User implements Serializable {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String pseudo;
private String password;
private String email;
private Gender gender;
@Lob
private byte[] avatar;
private String description;
private Date birthdate;

@ManyToMany(cascade = CascadeType.ALL)
private List<Game> favoriteGames = new ArrayList<>();

@OneToMany( cascade = CascadeType.ALL)
private List<User> friends = new ArrayList<>();

I tried @ManyToMany, @OneToMany, cascade = CascadeType.ALL

CodePudding user response:

Basically, first I would advise that you take special care with your equals and hashCode implementation in your entities. You did not show us that, but it should be something like this in your User.java:

@Override
public boolean equals(Object o) {
    if (this == o) {
        return true;
    }
    if (!(o instanceof User)) {
        return false;
    }
    User other = (User) o;
    return id != null && id.equals(other.getId());
}

@Override
public int hashCode() {
    return getClass().hashCode();
}

Those are very important, especially when working with entities in collections.

Secondly, a connection between a User and his Friends (other Users) should be modeled as Many-to-Many, because:

  • every user can be a friend to MANY of other users
  • every user can have any number of friends, in other words MANY friends

And I would model this connection like this:

@ManyToMany
@JoinTable(name = "user_friends", joinColumns = @JoinColumn(name = "user_id"),
        inverseJoinColumns = @JoinColumn(name = "friend_user_id"))
private Set<User> friends = new HashSet<>();
  • Related