0

下面是代码

 package com.hibernate.mapping.mtm;

    import java.util.ArrayList;
    import java.util.List;

    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.Transaction;
    import org.hibernate.cfg.Configuration;

    /**
     * @author Prajapati
     *
     */
    public class Main {


        /**
         * @param args
         */
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            SessionFactory sf= new Configuration().configure("com/hibernate/mapping/mtm/hibernate.cfg.xml").buildSessionFactory();
            Session sn  = sf.openSession();
            Transaction tx = sn.beginTransaction();


            Department dept1  = new Department();
            dept1.setId(20l);
            dept1.setDepartmentName("Development");


            Department dept2  = new Department();
            dept2.setId(10l);
            dept2.setDepartmentName("Accounts");

            Department dept3  = new Department();
            dept3.setId(30l);
            dept3.setDepartmentName("QA");

            Department dept4  = new Department();
            dept4.setId(40l);
            dept4.setDepartmentName("Designing");


            Employee emp1 = new Employee();
            emp1.setEmployeeID(30l);
            emp1.setEmployeeName("Michele");

            Employee emp2 = new Employee();
            emp2.setEmployeeID(40l);
            emp2.setEmployeeName("Devendra");


            Employee emp3 = new Employee();
            emp3.setEmployeeID(50l);
            emp3.setEmployeeName("Prabhat");

            Employee emp4 = new Employee();
            emp4.setEmployeeID(60l);
            emp4.setEmployeeName("Himanshi");

            Employee emp5 = new Employee();
            emp5.setEmployeeID(70l);
            emp5.setEmployeeName("Kanika");


            List<Employee> employeesQA = new ArrayList<Employee>();

            employeesQA.add(emp3);
            employeesQA.add(emp2);


            List<Employee> employeesDev = new ArrayList<>();

            employeesDev.add(emp3);
            employeesDev.add(emp4);


            List<Employee> employeesAccounts = new ArrayList<>();

            employeesAccounts.add(emp5);
            employeesAccounts.add(emp1);




            dept3.setEmployees(employeesQA);
            dept1.setEmployees(employeesDev);

            List<Department> departments = new ArrayList<Department>();

            departments.add(dept1);
            departments.add(dept2);
            departments.add(dept3);
            departments.add(dept4);

            //emp5 works in all the departments
            emp5.setDepartments(departments);


            /*List<Department> departments3 = new ArrayList<Department>();

            departments3.add(dept1);
            departments3.add(dept2);

            emp3.setDepartments(departments3);
             */


            sn.save(emp5);
            sn.save(dept3);
            sn.save(dept1);

            /**
             * When i am running this program. 
             * Only mapping from department side is mapped and not from inverse side.How can i say this is a M2M 
             * while i am unable to Map from both the sides in terms of Hibernate
             */

            //      sn.save(p);
            tx.commit();
            sn.close();


        }

    }

package com.hibernate.mapping.mtm;

    import java.util.List;

    import javax.persistence.CascadeType;
    import javax.persistence.Entity;
    import javax.persistence.Id;
    import javax.persistence.ManyToMany;


    @Entity
    public class Department {

        @Id
        private Long id;


        private String departmentName;

        //@ManyToMany(cascade=CascadeType.ALL,mappedBy="departments")
        @ManyToMany(cascade=CascadeType.ALL)
        private List<Employee> employees;

        public Long getId() {
            return id;
        }

        public void setId(Long id) {
            this.id = id;
        }

        public String getDepartmentName() {
            return departmentName;
        }

        public void setDepartmentName(String departmentName) {
            this.departmentName = departmentName;
        }

        public List<Employee> getEmployees() {
            return employees;
        }

        public void setEmployees(List<Employee> employees) {
            this.employees = employees;
        }



    }

package com.hibernate.mapping.mtm;

import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToMany;

@Entity
public class Employee {

    @Id
    private Long employeeID;

    private String employeeName;


    @ManyToMany(mappedBy="employees",cascade=CascadeType.ALL)
    //Mapped by says here that go to employees in opposite table to get details of departments for employees and the key of the relationship is on the other side.
    //i.e. you are considering department side the owner side now by saying mappedby.
    //@ManyToMany(cascade=CascadeType.ALL)
    private List<Department> departments;

    public Long getEmployeeID() {
        return employeeID;
    }

    public void setEmployeeID(Long employeeID) {
        this.employeeID = employeeID;
    }

    public String getEmployeeName() {
        return employeeName;
    }

    public void setEmployeeName(String employeeName) {
        this.employeeName = employeeName;
    }

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

    public void setDepartments(List<Department> departments) {
        this.departments = departments;
    }




}

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">org.gjt.mm.mysql.Driver</property>
        <property name="hibernate.connection.password">root</property>
        <property name="hibernate.connection.url">jdbc:mysql://127.0.0.1/mapping</property>
        <property name="hibernate.connection.username">root</property>
        <!-- <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property> -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>


        <property name="hbm2ddl.auto">create</property>
        <property name="show_sql">true</property>

     <mapping class="com.hibernate.mapping.mtm.Employee"/>
    <mapping class="com.hibernate.mapping.mtm.Department"/>

    </session-factory>
</hibernate-configuration>

我很困惑为什么 Hibernate 没有保存 emp5 的所有条目,因为它在所有部门中都是如此,而且关系是多对多的,没有为员工 emp5 完成条目。

以下是包含相应数据的表格:

mysql> select * from employee;


    | employeeID | employeeName |


    |         40 | Devendra     |

    |         50 | Prabhat      |

    |         60 | Himanshi     |

    |         70 | Kanika       |



    mysql> select * from department;



    | id | departmentName |


    | 10 | Accounts       |

    | 20 | Development    |

    | 30 | QA             |

    | 40 | Designing      |

    mysql> select * from department_employee;



    | departments_id | employees_employeeID |

    |             20 |                   50 |

    |             20 |                   60 |

    |             30 |                   50 |

    |             30 |                   40 |
4

1 回答 1

0

关联是双向的。双向关联有两个方面:所有者方和反方。Hibernate 在持久化时并不关心反面。它只考虑所有者方面。所有者方是不具有该mappedBy属性的一方。所以,这里的所有者是Department

您的代码将 dept1、dept2 等添加到 emp5。但它不会将 emp5 添加到 dept1、dept2 等。

因此,您的代码不仅使对象图不连贯(如果 dept1 在 emp5 的部门中,那么 dept1 应该在其员工列表中包含 emp5),而且它只初始化 Hibernate 不关心的那一侧。

于 2013-10-06T14:51:03.823 回答