zp26
zp26

Reputation: 1527

@ManyToMany Duplicate Entry Exception

I have mapped a bidirectional many-to-many exception between the entities Course and Trainee in the following manner:

Course
{
    ...
    private Collection<Trainee> students;
    ...
    @ManyToMany(targetEntity = lesson.domain.Trainee.class,
        cascade = {CascadeType.All}, fetch = {FetchType.EAGER})
    @Jointable(name="COURSE_TRAINEE",
        joincolumns = @JoinColumn(name="COURSE_ID"),
        inverseJoinColumns = @JoinColumn(name = "TRAINEE_ID"))
    @CollectionOfElements
    public Collection<Trainee> getStudents() {
        return students;
        }
    ...
}


Trainee
{
    ...
    private Collection<Course> authCourses;
    ...
    @ManyToMany(cascade = {CascadeType.All}, fetch = {FetchType.EAGER},
        mappedBy = "students", targetEntity = lesson.domain.Course.class)
    @CollectionOfElements
    public Collection<Course> getAuthCourses() {
        return authCourses;
    }
    ...
}

Instead of creating a table where the Primary Key is made of the two foreign keys (imported from the table of the related two entities), the system generates the table "COURSE_TRAINEE" with the following schema:

alt text

I am working on MySQL 5.1 and my App. Server is JBoss 5.1. Does anyone guess why?

Upvotes: 0

Views: 2632

Answers (2)

axtavt
axtavt

Reputation: 242786

In addition to Bence Olah: the primary key constraint for (COURSE_ID, TRAINEE_ID) pair is not created because your mapping doesn't say that these pairs are unique. You need to change Collections to Sets in your code in order to express this restriction, and primary key will be created.

Upvotes: 3

Bence Olah
Bence Olah

Reputation: 684

Use either @CollectionOfElements OR @ManyToMany. Don't use both of them at the same time! Be aware that @CollectionOfElements is Hibernate specific, while @ManyToMany is based on JPA standard.

Futher reading: http://docs.jboss.org/ejb3/app-server/HibernateAnnotations/reference/en/html_single/index.html

Upvotes: 2

Related Questions