Persistence: ManyToMany to same class

I am trying to set a ManyToMany annotation on my code:

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@Table(name = "user")
public class User extends AbstractUser 
{

    @ManyToMany(mappedBy = "promotors", cascade = CascadeType.PERSIST)
    @JoinTable(name = "user_student",
        joinColumns=@JoinColumn(name="promotor_id", referencedColumnName="id"),
        inverseJoinColumns=@JoinColumn(name="student_id", referencedColumnName="id")        
    )
    private Collection<User> students;

    @ManyToMany
    private Collection<User> promotors;
}

However every time i try to run the application and the db gets generated, it creates 2 tables for the ManyToMany, 1 new table that is called user_student as i defined beneath, but it also creates a second table user_user which i didn't define but is generated from the promotors.

Answers


It's correct you cannot map many to many relationship on one table. As you have only one possible column to map it to. What enforces one to one relationship.

You always have to have mapping table. Its also most convenient way to map many to many relationships on different tables.


Apparently, i didn't define the second ManyToMany correctly, this is the correct code:

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@Table(name = "user")
public class User extends AbstractUser 
{

    @ManyToMany
    @JoinTable(name = "user_student",
        joinColumns={@JoinColumn(name="promotor_id", referencedColumnName="id")},
        inverseJoinColumns={@JoinColumn(name="student_id", referencedColumnName="id")}        
    )
    private Collection<User> students;

    @ManyToMany(mappedBy = "students", cascade = CascadeType.PERSIST)
    private Collection<User> promotors;
}

Need Your Help

ProgressBar percentage disappears when Loading

c# winforms

Why does my progressbar percentage text disapear when progressbar starts loading??