Home > Software design >  How to join table with itself using another table in hibernate with annotations?
How to join table with itself using another table in hibernate with annotations?

Time:10-09

I have two tables - users and friends. Any user may have any number of friends (another users). These relationships are stored in a table 'friends', so this is just service table.

Pricture of relationships

How should I code this in my entity classes? Should I use @ManyToMany? My presumption is the next:

User.java:

@Entity
@Table(name = "users")
@NoArgsConstructor
public class User implements Serializable {

    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Id
    @Column(name = "id")
    private Long id;

    @Basic
    @Column(name = "name", nullable = false, length = 45)
    private String name;

    @ManyToMany(cascade = { CascadeType.ALL })
    @JoinTable(
            name = "friends",
            joinColumns = { @JoinColumn(name = "id") },
            inverseJoinColumns = { @JoinColumn(name = "sender") }
    )
    private Set<User> friendsInviters = new HashSet<>();

    @ManyToMany(mappedBy = "users")
    private Set<User> friendsReceiver = new HashSet<>();

}

Friend.java:

@Entity
@Table(name = "friends")
@NoArgsConstructor
public class Friend implements Serializable {

    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Id
    @Column(name = "id")
    private Long id;

    @Basic
    @Column(name = "sender")
    private Long sender;

    @Basic
    @Column(name = "receiver")
    private Long receiver;

}

P.S. - i just started to learn Hibernate:)

CodePudding user response:

@Entity
@Table(name = "users")
public class User implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long userId;

    @Column(name = "name", nullable = false, length = 45)
    private String name;

    @ManyToMany(cascade = { CascadeType.ALL })
    @JoinTable(name="users_friends",
            joinColumns = { @JoinColumn(name = "user_id") },
            inverseJoinColumns = { @JoinColumn(name = "friend_id") }
    )
    private Set<User> friendsInviters = new HashSet<>();

    @ManyToMany(mappedBy = "friendsInviters")
    private Set<User> friendsReceiver = new HashSet<>();

    public Long getUserId() {
        return userId;
    }

    public void setUserId(Long userId) {
        this.userId = userId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Set<User> getFriendsInviters() {
        return friendsInviters;
    }

    public void setFriendsInviters(Set<User> friendsInviters) {
        this.friendsInviters = friendsInviters;
    }

    public Set<User> getFriendsReceiver() {
        return friendsReceiver;
    }

    public void setFriendsReceiver(Set<User> friendsReceiver) {
        this.friendsReceiver = friendsReceiver;
    }
}

CodePudding user response:

@mildgrey

I tried this, but table friends is still empty when i add friend like this:

try (Session session = sessionFactory.openSession()) {

    session.getTransaction().begin();

    User user = session.getReference(User.class, 1L);
    User friend = session.getReference(User.class, 2L);

    user.getFriendsReceivers().add(friend);
    
    session.update(user);

    session.getTransaction().commit();

}

What i do wrong?

  • Related