Boa tarde, preciso finalizar meu TCC e infelizmente não estou conseguindo lidar com a relação many-to-many para fazer uma relação de amigos:
Basicamente o usuário tem uma tabela dele e uma chamada friends com duas chaves estrangeiras de usuarios vc e seu amigo.
User
private static final long serialVersionUID = 1638799445587638911L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
private String password;
@ManyToMany
@JoinTable(name = "friends", joinColumns = @JoinColumn(name = "userId"), inverseJoinColumns = @JoinColumn(name = "friendId"))
private List<User> friendsOf;
@ManyToMany
@JoinTable(name = "friends", joinColumns = @JoinColumn(name = "friendId"), inverseJoinColumns = @JoinColumn(name = "userId"))
private List<User> friends;
Controller
@GetMapping
public List<FriendDto> list(Long friend, Long friendOf) {
List<User> friends = friendRepository.findAll();
return FriendDto.convert(friends);
}
Repository
public interface FriendRepository extends JpaRepository<User, Long> {
Optional<User> findById(Long id);
}
Form
@NotNull
private Long friendsOf;
@NotNull
private Long friend;
public Long getFriendsOf() {
return friendsOf;
}
public void setFriendsOf(Long friendsOf) {
this.friendsOf = friendsOf;
}
public Long getFriend() {
return friend;
}
public void setFriend(Long friend) {
this.friend = friend;
}
public User create(FriendRepository friendRepository) {
User friendsOf = friendRepository.getOne(this.friendsOf);
User friend = friendRepository.getOne(this.friend);
User user = new User(friendsOf, friend);
return user;
}
Dto
private Long friends;
private Long friendsOf;
public Long getFriends() {
return friends;
}
public void setFriends(Long friends) {
this.friends = friends;
}
public Long getFriendsOf() {
return friendsOf;
}
public void setFriendsOf(Long friendsOf) {
this.friendsOf = friendsOf;
}
public FriendDto(User user) {
this.friends = user.getFriends().getId(); //Erro
this.friendsOf = user.getFriendsOf().getId(); //Erro
}
public static List<FriendDto> convert(List<User> users) {
return users.stream().map(FriendDto::new).collect(Collectors.toList());
}