Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA ManyToMany, how can JoinTable have a property?

I have a question for designing the ManyToMany in EJB, how can a jointable has a property?
Here is an example, the students and courses are ManyToMany, every student have many courses, and many students choose one course.

    @Entity
    public class Student implements Serializable { 
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        Long id;
        String name;
        private Collection<Course> courses; 

        @ManyToMany(mappedBy = "students",cascade=CascadeType.ALL)      
        public Collection<Course> getCourses() {
            return this.courses;
        }

        public void setCourses(Collection<Course> courses) {
            this.courses = courses;
        }

    }


    @Entity
    public class Course implements Serializable { 
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        Long id;
        String name; 
        private Collection<Student> students; 

        @ManyToMany(cascade=CascadeType.ALL)
        @JoinTable(name = "Student_Course",
        joinColumns = {@JoinColumn(name = "Course_ID", referencedColumnName = "id")}, 
        inverseJoinColumns = {@JoinColumn(name = "Student_ID", referencedColumnName = "id")})  

        public Collection<Student> getStudents() {
            return this.students;
        }

        public void setStudents(Collection<Student> students) {
            this.students = students;
        }
    }

However if I have a property in the JoinTable, for example each student has one score for one course. How can I make it in EJB with ManyToMany?
Many thanks for your attention!

like image 321
seaguest Avatar asked Dec 20 '11 21:12

seaguest


1 Answers

It is not possible, you cannot add property to relationship. If you need to access property in the join table, then that property belongs to some entity and as a result you need third entity.

like image 127
Yogu Avatar answered Oct 15 '22 05:10

Yogu