-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 1 post ] 
Author Message
 Post subject: insert into many-to-many relationship while staying lazy?
PostPosted: Mon Sep 26, 2011 6:13 pm 
Newbie

Joined: Sun Dec 30, 2007 1:08 pm
Posts: 14
Hi,
Example of a many-to-many relationship:
A student can be in n departments
A department can have m students.

The simplified mapping code looks like this:

Code:
@Entity
@Table(name="DEPARTMENT")
public class Department {

    @ManyToMany(mappedBy="departments", fetch=FetchType.LAZY, cascade= CascadeType.MERGE)
       @JoinTable(name="DEPARTMENT_STUDENT",
               joinColumns=
               @JoinColumn(name="DEPARTMENT_ID", referencedColumnName="DEPARTMENT_ID"),
         inverseJoinColumns=
               @JoinColumn(name="STUDENT_ID", referencedColumnName="STUDENT_ID")
       )
    private final List<Student> students= new ArrayList<Student>();


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

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

   @ManyToMany(mappedBy = "students", fetch = FetchType.LAZY, cascade= CascadeType.MERGE)
   private final List<Department> departments = new ArrayList<Department>();

   public List<Department> getDepartments() {
      return departments;
   }

}


Note that the mapping is set to lazy because I don't need to get all students and departments.
When I want to add a new student to an existing department I would program something link this:

Code:
Department department;
Student student;
//...
department.getStudents().add(student);
student.getDepartments().add(department);   


Here is my problem:
When I call department.getStudents(), the students List of the department object is queried from the database.
This has a noticeable performance impact (memory and execution time) if a department has many students.
Everything I really want to do at this point is to add a new record into the mapping table for department and students.

Is there a way to add to a lazy bidirectional many-to-many relationship without retrieving one or both ends of the relationship?


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 1 post ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.