0

I would like to perform nested join, where my class User will contain list of Users analogus to SQL query:

SELECT user1.id, user2.id FROM ( users user1 LEFT JOIN friends friend ON user1.id=friend.who ) LEFT JOIN users user2 ON friend.with=user2.id GROUP BY user1.id, user2.id

My User entity class:

@Entity
@Table(name = "users")
public class User implements Serializable {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name = "id")
    private Integer id;
    @Column(name = "login")
    private String login;
    @Column(name = "name")
    private String name;
    @Column(name = "lastname")
    private String surname;
    @Column(name = "password")
    private String password;
    @ManyToMany
    ????
    private List<User> users;
}

Relation between users - FriendRelation entity class:

@Entity
@Table(name="friends")
public class FriendRelation implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private Integer id;
    @Column(name = "who")
    private Integer who;
    @Column(name = "with")
    private Integer with;
    @OneToMany
    @JoinColumn(name="with", referencedColumnName = "id")
    private List<User> users;
}

who - refers to id of user
with - refers to id of user in friend relationship with user who

What sould I put in place of "????" to acheive it?

I'm using Spring Data JPA

1 Answer 1

1

The solution was to add annotation @JoinTable.
We can use this annotation to join two tables using mapping table, in this case, it is inverse join.

@JoinTable(name = "friends", joinColumns = @JoinColumn(name = "who"), inverseJoinColumns = @JoinColumn(name = "with"))

User class:

@Entity
@Table(name = "users")
public class User implements Serializable {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name = "id")
    private Integer id;
    @Column(name = "login")
    private String login;
    @Column(name = "name")
    private String name;
    @Column(name = "lastname")
    private String surname;
    @Column(name = "password")
    private String password;
    @ManyToMany
    @JoinTable(name = "friends", joinColumns = @JoinColumn(name = "who"), inverseJoinColumns = @JoinColumn(name = "with"))
    private List<User> friends;
}

Here is perfectly explained how to deal with this situation.
Hope it helps someone.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.