How Do I Create Many to Many Hibernate Mapping for Additional Property from the Join Table?

前端 未结 1 1312
我在风中等你
我在风中等你 2020-11-28 09:31

I need a many to many hibernate mapping needed 3 joins. I\'ve tried to find out a solution without intermediate entity like LecturerCourse.

I have a man

相关标签:
1条回答
  • 2020-11-28 09:57

    You need to use @EmbeddedId and @Embeddable annotations to solve this issue:

    Lecturer Class:

    @Entity
    @Table(name="LECTURER")
    public class Lecturer {
    
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.lecturer", cascade=CascadeType.ALL)
    Set<LecturerCourse> lecturerCourses == new HashSet<LecturerCourse>();
    
    //all others properties Setters and getters are less relevant.
    
    }
    

    Course class:

    @Entity
    @Table(name="COURSE")
    public class Course {
    
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.course", cascade=CascadeType.ALL)
    Set<LecturerCourse> lecturerCourses == new HashSet<LecturerCourse>();
    
    //all others properties Setters and getters are less relevant.
    
    }
    

    LecturerCourse Class:

    @Entity
    @Table(name = "lecturer_course")
    @AssociationOverrides({
            @AssociationOverride(name = "pk.lecturer", 
                joinColumns = @JoinColumn(name = "LECTURER_ID")),
            @AssociationOverride(name = "pk.course", 
                joinColumns = @JoinColumn(name = "COURSE_ID")) })
    public class LecturerCourse {
    
        private LecturerCourseID pk = new LecturerCourseID();
    
        @Column(name = "CAPACITY", nullable = false, length = 10)
        private String capacity;
    
        @EmbeddedId
        public LecturerCourseID getPk() {
            return pk;
        }
    
    }
    

    Now the Primary Key:

    @Embeddable
    public class LecturerCourseID implements java.io.Serializable {
    
        private Lecturer lecturer;
        private Course course;
    
        @ManyToOne
        public Stock getLecturer() {
            return lecturer;
        }
    
        public void setLecturer(Lecturer lecturer) {
            this.lecturer= lecturer;
        }
    
        @ManyToOne
        public Course getCourse() {
            return course;
        }
    
        public void setCourse(Course course) {
            this.course= course;
        }
    
    }
    

    now Your Main should be something like this:

    Lecturer lecturer1 = new Lecturer();
    Course math = new Course();
    LecturerCourse lecturer1math  = new LecturerCourse();
    lecturer1math.setCapacity("capacity");
    lecturer1math.setLecturer(lecturer1);
    lecturer1math.setCourse(math);
    lecturer1.getLecturerCourses().add(lecturer1math);
    
    //saving object
    session.save(lecturer1);
    

    You need to be sure that class marked as @Embeddable should implement Serializable marker interface.

    Hope it helps.

    0 讨论(0)
提交回复
热议问题