5 Replies Latest reply: May 8, 2012 5:30 AM by EJP RSS

    Problem with one to many relationship

    Prem
      Hi I am implementing JPA hibernate simple application using one to many relationship.

      Relation ship is Comapny (1)----------- Department(*)

      Company.java is as follow :
      package com.web.pojo;
      
      import java.util.ArrayList;
      import java.util.List;
      
      import javax.persistence.Entity;
      import javax.persistence.FetchType;
      import javax.persistence.GeneratedValue;
      import javax.persistence.Id;
      import javax.persistence.JoinColumn;
      import javax.persistence.JoinTable;
      import javax.persistence.OneToMany;
      
      import org.hibernate.annotations.Cascade;
      
      
      
      @Entity
      public class Company {
           
            
           @Id
           @GeneratedValue
           private int compId;
           private String companyName;
           
           @OneToMany(fetch=FetchType.LAZY)
           @JoinColumn(name="compId")
           @Cascade(org.hibernate.annotations.CascadeType.ALL)
           private List <Department> listOfDepartment = new ArrayList<Department>();
           
           
           public List<Department> getListOfDepartment() {
                return listOfDepartment;
           }
           public void setListOfDepartment(List<Department> listOfDepartment) {
                this.listOfDepartment = listOfDepartment;
           }
           public int getCompanyId() {
                return compId;
           }
           public void setCompanyId(int companyId) {
                this.compId = companyId;
           }
           public String getCompanyName() {
                return companyName;
           }
           public void setCompanyName(String companyName) {
                this.companyName = companyName;
           }
      
      }
      Department.java is as follow :
      package com.web.pojo;
      
      import java.util.ArrayList;
      import java.util.List;
      
      import javax.persistence.CascadeType;
      import javax.persistence.Entity;
      import javax.persistence.FetchType;
      import javax.persistence.GeneratedValue;
      import javax.persistence.Id;
      import javax.persistence.JoinColumn;
      import javax.persistence.JoinTable;
      import javax.persistence.ManyToMany;
      import javax.persistence.ManyToOne;
      import javax.persistence.OneToMany;
      
      import org.hibernate.annotations.Cascade;
      
      
      @Entity
      public class Department {
           
           @Id
           @GeneratedValue
           private int deptId;
           private String deptName;
      
           @ManyToOne
           @JoinColumn(name="compId")
           private Company company;
           
           @OneToMany(cascade=CascadeType.ALL,fetch=FetchType.LAZY)
           private List<Employee>listofEmployee = new ArrayList<Employee>();
           
           
           public int getDeptId() {
                return deptId;
           }
           public void setDeptId(int deptId) {
                this.deptId = deptId;
           }
           public String getDeptName() {
                return deptName;
           }
           public void setDeptName(String deptName) {
                this.deptName = deptName;
           }
           public Company getCompany() {
                return company;
           }
           public void setCompany(Company company) {
                this.company = company;
           }
           public List<Employee> getListofEmployee() {
                return listofEmployee;
           }
           public void setListofEmployee(List<Employee> listofEmployee) {
                this.listofEmployee = listofEmployee;
           }
           
      
      }
      CompanyDAO.java is follow
      package com.web.hibernatetier;
      
      import java.util.ArrayList;
      import java.util.List;
      
      import com.web.HibernateUtil;
      import com.web.pojo.Company;
      import com.web.pojo.Department;
      
      public class CompanyDAO {
           
                     
      
                    public void addCompany(Company company) {
                     
                     HibernateUtil.startHibernateSession();
                     HibernateUtil.session.save(company);
                     HibernateUtil.endHibernateSession();
                     
                }
                
                public void addDepartmentToCompany(Department department,int compId) {
                     
                     HibernateUtil.startHibernateSession();
                     Company company = (Company) HibernateUtil.session.get(Company.class, compId);
                     company.getListOfDepartment().add(department);
                     Department dept = company.getListOfDepartment().get(0);
                     System.out.println(dept.getCompany().getCompanyName());
                     HibernateUtil.endHibernateSession();
                }
                
                
                
                public static void main(String[] args) {
                     
                     
                               CompanyDAO dao = new CompanyDAO();
      
                              Company company = new Company();
                     company.setCompanyName("ABC");
      
                               dao.addCompany(company);
                     
      
                     
                     dao.addCompany(company);
                
                     // Department Transactions
      
                     
                     Department department = new Department();
                     department.setDeptName("Development");
                     
                     dao.addDepartmentToCompany(department, 1);
                     
                }
      
      
      
      }
      HibernateUtil.java
      public class HibernateUtil {
           
           private static SessionFactory sessionFactory ;
           public static Session session;
           
           private HibernateUtil() {
                
           }
           
           private static SessionFactory getSessionFactory() {
                
                if(sessionFactory==null) {
                      sessionFactory = new Configuration().configure().buildSessionFactory();
                }
                return sessionFactory;
                
           }
           
           
           public static void startHibernateSession() {
                
                sessionFactory = getSessionFactory();
                session = sessionFactory.openSession();
                session.beginTransaction();
           }
           
           
           public static void endHibernateSession() {
                session.getTransaction().commit();
                session.close();
           }
           
      
      }
      What I am doing is , I am adding new department to existing company. After execution above code

      Table created are :
      1. Company table with id and name
      2. Department table with deptId , deptName , compId.

      so at the time adding department , it does not threw any exception but updates records in department as
      1(Id),Development(DeptName),null(compId) .

      I am not getting why it is not updating compId column. Please help.
        • 1. Re: Problem with one to many relationship
          EJP
          No Servlet here. Your post is off topic for this forum.
          • 2. Re: Problem with one to many relationship
            Prem
            EJP wrote:
            No Servlet here. Your post is off topic for this forum.
            Yes I know , I have also posted same question on hibernate forum as well but not getting much help . That't why I posted here ...
            • 3. Re: Problem with one to many relationship
              gimbal2
              1: The @JoinColumn on the listOfDepartments collection in Company is wrong. It should be something like this for a bidirectional relationship:
              @OneToMany(mappedBy="company") // company is the matching property name in Department
              private List <Department> listOfDepartment = new ArrayList<Department>();
              Note that I removed the fetch configuration; onetomany is fetched lazy by design. Saves some clutter eh.

              2: use a Set in stead of a List (hibernate doesn't like lists much in entities and will break when you create slightly more complex entity relations)
              3: don't just slap cascades on collections, especially of type ALL. Do it with care. In the many years I've been using JPA I've only had to cascade deletes in very specific situations, maybe once or twice. I never needed any of the other cascade types, they just invite sloppy code if you ask me. When working with persistence you should apply a little precision.
              • 4. Re: Problem with one to many relationship
                Prem
                gimbal2 wrote:
                1: The @JoinColumn on the listOfDepartments collection in Company is wrong. It should be something like this for a bidirectional relationship:
                @OneToMany(mappedBy="company") // company is the matching property name in Department
                private List <Department> listOfDepartment = new ArrayList<Department>();
                Note that I removed the fetch configuration; onetomany is fetched lazy by design. Saves some clutter eh.

                2: use a Set in stead of a List (hibernate doesn't like lists much in entities and will break when you create slightly more complex entity relations)
                3: don't just slap cascades on collections, especially of type ALL. Do it with care. In the many years I've been using JPA I've only had to cascade deletes in very specific situations, maybe once or twice. I never needed any of the other cascade types, they just invite sloppy code if you ask me. When working with persistence you should apply a little precision.
                I made all changes as you mentioned but still compID in department table shows null value...
                • 5. Re: Problem with one to many relationship
                  EJP
                  That't why I posted here ...
                  No it isn't. This is a Java Servlet forum. You are not writing a Java Servlet. Your post is therefore off topic. There are plently of other forums here: some of them are even on-topic for your post.

                  Locking this thread.