0

I have the following situation: A user entity can have a lot of friends who are also users themselves.

To resolve this situation I used this answer Hibernate recursive many-to-many association with the same entity

It works! But not completely. After I put data into table TBL_FRIENDS the data is saved as I expected but then the getById function of the interface JpaRepository returns NULL for users I entered into the TBL_FRIENDS table.

this is my code:

package com.example.demo.user;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
 
@Entity
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column(name = "username", nullable = false)
    private String username;
    @Column(name = "gender", nullable = false)
    private String gender;
    @Column(name = "date", nullable = true)
    private Date date;
    @Column(name = "phone", nullable = false)
    private String phone;   
    @Column(name = "email", nullable = false)
    private String email;
    @Column(name = "description", nullable = true)
    private String description;
    @Column(name = "hashpassword", nullable = false)
    private String hashpassword;

    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(name="tbl_friends",
     joinColumns=@JoinColumn(name="personId"),
     inverseJoinColumns=@JoinColumn(name="friendId")
    )
    private List<User> friends = new ArrayList<>();

    @ManyToMany(mappedBy = "friends")
    @JoinTable(name="tbl_friends",
     joinColumns=@JoinColumn(name="friendId"),
     inverseJoinColumns=@JoinColumn(name="personId")
    )
    private List<User> friendOf = new ArrayList<>();
           
    protected User() {
        
    } 

    public User(Long id, String username, String gender,Date date, String phone, String email, String description,String hashpassword ) {
        super();
        this.id = id;
        this.username = username;
        this.gender = gender;
        this.date = date;
        this.phone = phone;
        this.email = email;
        this.description = description;
        this.hashpassword = hashpassword;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }


    public String getEmail() {
        return email;
    }


    public void setEmail(String email) {
        this.email = email;
    }
    
    public String getDescription() {
        return description;
    }


    public void setDescription(String description) {
        this.description = description;
    }
    
    public String getHashpassword() {
        return hashpassword;
    }

    public void setHashpassword(String hashpassword) {
        this.hashpassword = hashpassword;
    }

    public List<User> getFriends() {
        return friends;
    }

    public void addFriends(User friend) {
        this.friends.add(friend);
    }
    
    public List<User> getFriendOf() {
        return friendOf;
    }

    public void addFriendOf(User friend) {
        this.friendOf.add(friend);
    }
    
    @Override
    public int hashCode() {
        return Objects.hash(id);
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        User other = (User) obj;
        return id == other.id;
    }
}
public void insertUserAndFriends(User sourceUser,User targetUser) { 
    User su = userJpaRepository.getOne(sourceUser.getId());
    su.addFriends(targetUser);
    su.addFriendOf(targetUser);
    userJpaRepository.save(su);
}
@PostMapping("/jpa/users/{userId}/friends")
public ResponseEntity<Void>insertFriends(@RequestBody Map<String,User> jason){
  userJpaRepository.insertUserAndFriends(jason.get("sourceUser"),jason.get("targetUser"));  
    return ResponseEntity.ok().build();     
}
@GetMapping("/jpa/users/{userId}")
public User getUser(@PathVariable Long userId){
    return userJpaRepository.findById(userId).get();
}

I would like to hear any advice.:

João Dias
  • 16,277
  • 6
  • 33
  • 45

1 Answers1

0

Maybe your request has id's value is null or you can use :

@GeneratedValue(strategy = GenerationType.AUTO)
Elikill58
  • 4,050
  • 24
  • 23
  • 45