Bravo
Bravo

Reputation: 1139

Many-To-Many with only one Collections in the same entity?

I have the following entity:

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

    ...

    private List<User> connections;

    ...

}

Assume there are Users A and B. User A decides to add User B to his connections list. Connections list of A must contain User B and connection list of B must contain User A.

Considering my business logic, I have concluded that Many-To-Many relationship has to be used. I have found this question (link) on Stackoverflow, but this is not exactly what I was looking for. I want to store only one List in my entity class instead of two.

How can I implement this? I assume there must be two lists to create Many-To-Many relationship, so I guess my decision is incorrect.

Upvotes: 1

Views: 168

Answers (1)

void
void

Reputation: 7880

assuming you have a table user_users(user_1_id,user_2_id) in your database for the many-to-many relationship between users you can do something like this:

@Entity
@Table(name = "users")
public class User {
    private List<User> connections;

}

and now you can have the getConnection getter like this:

@ManyToMany(targetEntity=User.class)
@JoinTable(
    name="user_users",
    joinColumns=@JoinColumn(name="user_1_id", nullable=false),
    inverseJoinColumns=@JoinColumn(name="user_2_id", nullable=false)
)
public Set<ElementBean> getConnections() {
    return connections;
}

and you can add users to user like this:

public void addConnection(User usr) {
    if (usr !=null) { 
        connections.add(usr);
        usr.getConnections().add(this); 
    }    
}

Upvotes: 1

Related Questions