[jboss-user] [EJB 3.0] - Many to Many realtionship question

EladKatz do-not-reply at jboss.com
Thu Aug 13 13:10:24 EDT 2009


Hi,
I'm using a manyToMany relationship in my project and I have a question:
Is it possible to update the relationship from both sides?
I'll show you an example of what i mean:



  | @Entity
  | public class Student {
  |   @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
  |   private int id;
  |   private String name;
  | 
  |   @ManyToMany 
  |   @JoinTable(name="Student_Dept", 
  |       joinColumns=@JoinColumn(name="Stut_ID"),
  |       inverseJoinColumns=@JoinColumn(name="DEPT_ID"))  
  |   private Collection<Department> departments;
  |   public Student() {
  |     departments = new ArrayList<Department>();
  | }
  | ...
  |   public Collection<Department> getDepartments() {
  |     return departments;
  |   }
  | 
  |   public void setDepartment(Collection<Department> departments) {
  |     this.departments = departments;
  |   }
  | 

  | @Entity
  | public class Department {
  |     @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
  |     private int id;
  |     private String name;
  | 
  |     @ManyToMany(mappedBy="departments")
  |     private Collection<Student> students;
  |     
  |     public Department(){
  |       students = new ArrayList<Student>();
  |     }
  | ...
  |     public Collection<Student> getStudents() {
  |       return students;
  |     }
  | 
  |     public void setStudent(Collection<Student> students) {
  |       this.students = students;
  |     }
  | 

Given that, In my main.java I can do this:

  | Department dept = new Department();
  | ...
  |     dept.addStudent(student1);
  |     em.persist(dept);
  | 
and it works
but if i try it the other way around

  |     student.addDept(dept1);
  | 
it fails to update the database (no exception or anything - the changes simply do not reflect in the db)
is that because i have to do it from one side only?

note:
This example is not my code but was taken from:  http://www.java2s.com/Tutorial/Java/0355__JPA/ManyToManyJoinTableJoinInverseJoinColumn.htm
it is similar enough though that you can use it as a reference.

Thanks,
Elad Katz


View the original post : http://www.jboss.org/index.html?module=bb&op=viewtopic&p=4249486#4249486

Reply to the post : http://www.jboss.org/index.html?module=bb&op=posting&mode=reply&p=4249486



More information about the jboss-user mailing list