开发者

@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;
    开发者_StackOverflow...
    @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:

@ManyToMany Duplicate Entry Exception

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


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜