使用一对一关系hibernate进行更新

时间:2017-03-21 04:18:54

标签: java mysql spring hibernate

我有一个父对象作为Employee,子对象作为Address。我只需要使用Employee对象更新这两个对象。但是当使用employee对象进行更新时,我只是获取emp_id不应为null。这是我的表和实体

Scanner infile = new Scanner(new FileInputStream("‪C:/Users/Josh/Desktop/prog5input.csv"));

地址表

CREATE TABLE `employee` (
`employee_id` bigint(20) NOT NULL AUTO_INCREMENT,
`employee_name` varchar(30) NOT NULL,
`employee_desg` varchar(30) NOT NULL,
`salary` varchar(30) NOT NULL,
`employee_reference_id` varchar(10) NOT NULL,
PRIMARY KEY (`employee_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8

员工对象

CREATE TABLE `address` (
`address_id` bigint(20) NOT NULL AUTO_INCREMENT,
`emp_id` bigint(20) NOT NULL,
`address` varchar(255) NOT NULL,
PRIMARY KEY (`address_id`),
KEY `employee_address` (`emp_id`),
CONSTRAINT `employee_address` FOREIGN KEY (`emp_id`) REFERENCES `employee`   (`employee_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8

地址对象

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;

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

@Id
@GeneratedValue
@Column(name = "EMPLOYEE_ID")
private int id;

@Column(name = "EMPLOYEE_NAME")
private String employeeName;

@Column(name = "EMPLOYEE_DESG")
private String employeeDesg;

@Column(name = "SALARY")
private String salary;

@Column(name = "EMPLOYEE_REFERENCE_ID")
private String employeeReferenceId;

public String getEmployeeReferenceId() {
    return employeeReferenceId;
}

public void setEmployeeReferenceId(String employeeReferenceId) {
    this.employeeReferenceId = employeeReferenceId;
}

@OneToOne(mappedBy="employee", cascade = CascadeType.ALL)
private Address address;


public String getEmployeeName() {
    return employeeName;
}

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

public String getEmployeeDesg() {
    return employeeDesg;
}

public void setEmployeeDesg(String employeeDesg) {
    this.employeeDesg = employeeDesg;
}

public String getSalary() {
    return salary;
}

public void setSalary(String salary) {
    this.salary = salary;
}

public Address getAddress() {
    return address;
}

public void setAddress(Address address) {
    this.address = address;
}

public int getId() {
    return id;
}

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

}

我的代码是

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;



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

@Id
@Column(name="ADDRESS_ID")
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;

@Column(name = "ADDRESS")
private String address;
@OneToOne(fetch=FetchType.EAGER , cascade=CascadeType.ALL, orphanRemoval=true)
@JoinColumn(name="emp_id",referencedColumnName="employee_id")
private Employee employee;

public String getAddress() {
    return address;
}

public void setAddress(String address) {
    this.address = address;
}

public Employee getEmployee() {
    return employee;
}

public void setEmployee(Employee employee) {
    this.employee = employee;
}

public Address() {

}

public int getId() {
    return id;
}

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

错误是

public class StudentUtil1To1 {
public static void main(String args[]){
    SessionFactory factory=null;
    Configuration configuration=null;
    ServiceRegistry registry=null;
    Session session=null;
    try{
        configuration= new Configuration();
        configuration.configure();
        registry=new StandardServiceRegistryBuilder().configure().applySettings(configuration.getProperties()).build();
        factory=configuration.configure("hibernate.cfg.xml").buildSessionFactory(registry);
        session= factory.openSession();
        session.beginTransaction();


            Employee emp=new Employee();
            emp.setId(1);
            emp.setEmployeeReferenceId("CP001");
            emp.setEmployeeName("Muthu");
            emp.setEmployeeDesg("Developer");
            emp.setSalary("15000");

            Address address=new Address();
            address.setAddress("3, Civil aerodrome, CBE");


            emp.setAddress(address);
            address.setEmployee(emp);
            session.update(emp);



        System.out.println("Successfuly Saved");
        session.getTransaction().commit();

    }catch(Exception e){
        e.printStackTrace();
    }finally{
        if(session!=null){
            session.close();
        }
        if(factory!=null){
            factory.close();
        }
    }
}
}

我需要更新的内容。纠正我的错误。

2 个答案:

答案 0 :(得分:1)

由于您已经在员工实体中映射了地址实体,因此

@OneToOne(mappedBy="employee", cascade = CascadeType.ALL)
private Address address;

你不必在地址类中做同样的事情

@OneToOne(fetch=FetchType.EAGER , cascade=CascadeType.ALL, orphanRemoval=true)
@JoinColumn(name="emp_id",referencedColumnName="employee_id")
private Employee employee;

地址实体中不需要上述代码。地址类 删除 员工属性。 现在您已经在 OneToOne 注释中添加了 CascadeType.ALL ,并且只保存了像这样的员工对象

 Employee emp=new Employee();
            Address address=new Address("your address");
            emp.setAddress(address);
            emp.setId(1);
            emp.setEmployeeReferenceId("CP001");
            emp.setEmployeeName("Muthu");
            emp.setEmployeeDesg("Developer");
            emp.setSalary("15000");
            session.update(emp);

答案 1 :(得分:0)

1. @ MapppedBy注释意味着:@ MapppedBy注释的实体,放弃键的引用,所以在employee表中,没有名为“address_id”的列。 Employee和Address之间的关系由“地址”表控制。 2.当你使用[session.update(emp);]时,你没有“Employee”表的数据。但是emp_id是FOREIGN KEY,所以会出现这个问题 3.我可以先插入Employee,然后插入[session.update(emp);]