Hibernate many-to-many relationship

Posted by Capitan on Stack Overflow See other posts from Stack Overflow or by Capitan
Published on 2012-11-02T16:07:30Z Indexed on 2012/11/02 17:02 UTC
Read the original article Hit count: 146

Filed under:
|
|

I have two mapped types, related many-to-many.

@Entity
@Table(name = "students")
public class Student{

...

@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(
    name = "students2courses",
    joinColumns = { @JoinColumn(
        name = "student_id",
        referencedColumnName = "_id") },
    inverseJoinColumns = { @JoinColumn(
        name = "course_id",
        referencedColumnName = "_id") })

public Set<Course> getCourses() {
    return courses;
}

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

...
}

__

@Entity
@Table(name = "courses")
public class Course{

...

@ManyToMany(fetch = FetchType.EAGER, mappedBy = "courses")

public Set<Student> getStudents() {
    return students;
}

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

...
}

But if I update/delete Course entity, records are not created/deleted in table students2courses. (with Student entity updating/deleting goes as expected)

I wrote abstract class HibObject

public abstract class HibObject {
    public String getRemoveMTMQuery() {
        return null;
    }
}

which is inherited by Student and Course.

In DAO I added this code (for delete() method):

String query = obj.getRemoveMTMQuery();
if (query != null) {
    session.createSQLQuery(query).executeUpdate();
}

and I ovrerided method getRemoveMTMQuery() for Course

@Override
@Transient
public String getRemoveMTMQuery() {
    return "delete from students2courses where course_id = " + id + ";";
}

Now it works but I think it's a bad code.

Is there a best way to solve this problem?

© Stack Overflow or respective owner

Related posts about java

Related posts about hibernate