Hibernate多对多关联+连接表+额外列更新无法正常工作

时间:2014-04-18 06:21:56

标签: hibernate jpa

我正在举个例子。我有一个与Address Class有多对多关系的Employee类。我使用复合键在我的连接表中插入数据,该连接表有一个额外的列城市。

My All Pojos

//员工类

package com.test.manyToMany;

import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
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.OneToMany;

import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.GenericGenerator;

@Entity(name="EMPLOYEE")
public class Employee {

    private int id;
    private String name;
    private List<EmployeeAddress> employeeAddress;

    @Id
    @GenericGenerator(name="generator",strategy="increment")
    @GeneratedValue(generator="generator")
    @Column(name="ID",nullable=false,unique=true)
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }

    @Column(name="NAME")
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    @OneToMany(fetch=FetchType.LAZY,mappedBy="pk.employee")
     @Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE, 
            org.hibernate.annotations.CascadeType.DELETE_ORPHAN})
    public List<EmployeeAddress> getEmployeeAddress() {
        return employeeAddress;
    }
    public void setEmployeeAddress(List<EmployeeAddress> employeeAddress) {
        this.employeeAddress = employeeAddress;
    }

}

//地址类

package com.test.manyToMany;

import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;

import org.hibernate.annotations.GenericGenerator;

@Entity(name="ADDRESS")
public class Address {

    private int id;
    private String place;
    private List<EmployeeAddress> employeeAddress;

    @Id
    @GenericGenerator(name="generator",strategy="increment")
    @GeneratedValue(generator="generator")
    @Column(name="ID")
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }

    @Column(name="PLACE")
    public String getPlace() {
        return place;
    }
    public void setPlace(String place) {
        this.place = place;
    }

    @OneToMany(fetch=FetchType.LAZY,mappedBy="pk.address")
    public List<EmployeeAddress> getEmployeeAddress() {
        return employeeAddress;
    }

    public void setEmployeeAddress(List<EmployeeAddress> employeeAddress) {
        this.employeeAddress = employeeAddress;
    }
}

//员工地址

package com.test.manyToMany;

import java.io.Serializable;

import javax.persistence.AssociationOverride;
import javax.persistence.AssociationOverrides;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.Table;
import javax.persistence.Transient;


@Entity
@Table(name="EMPLOYEE_T_ADDRESS")
@AssociationOverrides({
    @AssociationOverride(name="pk.employee",
            joinColumns=@JoinColumn(name="EMPLOYEE_ID")),
    @AssociationOverride(name="pk.address",
            joinColumns=@JoinColumn(name="ADDRESS_ID"))})
public class EmployeeAddress implements Serializable{

    private static final long serialVersionUID = 4050660680047579957L;
    private EmployeeAddressId pk=new EmployeeAddressId();
    private String city;

    @EmbeddedId
    public EmployeeAddressId getPk() {
        return pk;
    }

    @Transient
    public Employee getEmployee() {
        System.out.println("Primary Key:"+getPk());
        return getPk().getEmployee();
    }

    public void setEmployee(Employee employee) {
        getPk().setEmployee(employee);
    }

    @Transient
    public Address getAddress() {
        System.out.println("Primary Key1:"+getPk());
        return getPk().getAddress();
    }

    public void setAddress(Address address) {
        getPk().setAddress(address);
    }

    public void setPk(EmployeeAddressId pk) {
        this.pk = pk;
    }

    @Column(name="CITY",length=50)
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((city == null) ? 0 : city.hashCode());
        result = prime * result + ((pk == null) ? 0 : pk.hashCode());
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        EmployeeAddress other = (EmployeeAddress) obj;
        if (city == null) {
            if (other.city != null)
                return false;
        } else if (!city.equals(other.city))
            return false;
        if (pk == null) {
            if (other.pk != null)
                return false;
        } else if (!pk.equals(other.pk))
            return false;
        return true;
    }   

}

// EmployeeAddressId

package com.test.manyToMany;

import java.io.Serializable;

import javax.persistence.CascadeType;
import javax.persistence.Embeddable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;

@Embeddable
public class EmployeeAddressId implements Serializable{

    private static final long serialVersionUID = -9120607274421816301L;
    private Employee employee;
    private Address address;

    @ManyToOne
    public Employee getEmployee() {
        return employee;
    }
    public void setEmployee(Employee employee) {
        this.employee = employee;
    }

    @ManyToOne
    public Address getAddress() {
        return address;
    }
    public void setAddress(Address address) {
        this.address = address;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((address == null) ? 0 : address.hashCode());
        result = prime * result
                + ((employee == null) ? 0 : employee.hashCode());
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        EmployeeAddressId other = (EmployeeAddressId) obj;
        if (address == null) {
            if (other.address != null)
                return false;
        } else if (!address.equals(other.address))
            return false;
        if (employee == null) {
            if (other.employee != null)
                return false;
        } else if (!employee.equals(other.employee))
            return false;
        return true;
    }

}

当我使用我的主类在db中插入一些数据时,一切正常。

package com.test.manyToMany;

import java.util.ArrayList;

import org.hibernate.Session;

import com.test.utils.HibernateUtil;

public class TestManyToMany {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Session session=HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();

        Employee employee1=new Employee();
        EmployeeAddress employeeAddress=new EmployeeAddress();
        Address address=new Address();
        ArrayList<EmployeeAddress> list=new ArrayList<EmployeeAddress>();
        address.setId(1);

        employee1.setName("XYZ");
        employeeAddress.setCity("CDE");
        employeeAddress.setEmployee(employee1);
        employeeAddress.setAddress(address);
        list.add(employeeAddress);
        employee1.setEmployeeAddress(list);

        session.save(employee1);
        session.getTransaction().commit();

    }

}

但是当我用地址id 2更新相同的记录时。

package com.test.manyToMany;

import java.util.ArrayList;

import org.hibernate.Session;

import com.test.utils.HibernateUtil;

public class TestManyToMany {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Session session=HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();

        Employee employee1=new Employee();
        EmployeeAddress employeeAddress=new EmployeeAddress();
        Address address=new Address();
        ArrayList<EmployeeAddress> list=new ArrayList<EmployeeAddress>();
        address.setId(2);
        //session.save(address);
        employee1.setId(1);
        employee1.setName("XYZ");
        employeeAddress.setCity("CDE");
        employeeAddress.setEmployee(employee1);
        employeeAddress.setAddress(address);
        list.add(employeeAddress);
        employee1.setEmployeeAddress(list);
        //address.setEmployeeAddress(list);
        //session.save(employee1);


        session.update(employee1);
        session.getTransaction().commit();

    }

}

我的联接表未删除

的第一条记录
+-----------+----------+----+
|EMPLOYEE_ID|ADDRESS_ID|CITY|
+-----------+----------+----+
| 1         |     1    |CDE |
+-----------+----------+----+

它也插入第二条记录

+-----------+----------+----+
|EMPLOYEE_ID|ADDRESS_ID|CITY|
+-----------+----------+----+
| 1         |     1    |CDE |
+-----------+----------+----+
|1          |     2    |CDE |
+-----------+----------+----+

我的拳头记录应该被删除然后它应该插入第二条记录。这是没有发生的。

0 个答案:

没有答案