简体   繁体   English

为什么关联表无法使用Hibernate正确更新?

[英]Why Associated table not updating properly using hibernate?

I have created Employee and Department entities. 我创建了员工和部门实体。 These are having bidirectional many-to-one and one-to-many relation. 它们具有双向的多对一和一对多关系。

Using REST client, I add department and employees. 使用REST客户端,我添加了部门和员工。

Adding Department: 新增部门:

{
  "name":"IT"
}

在此处输入图片说明

Adding Employee: 新增员工:

{"name": "Emp01" ,
 "address": 
    {
     "street" :"Street01" ,
     "city" :"City01" ,
     "state" :"State01" ,
     "country" :"Country01"
    },
 "department":{"id":"1"}
}

在此处输入图片说明

Now, I want to add a new department by associating an existing employee. 现在,我想通过关联现有员工来添加新部门。

{
  "name":"Admin",
  "employees":
  [{
      "id":3
    }]
}

在此处输入图片说明

在此处输入图片说明

Now, department is added successfully but employee table is not updated properly. 现在,部门已成功添加,但员工表未正确更新。 Except id other fields are blanked out. 除id外,其他字段均被清空。 Ideally, hibernate should have updated employee with latest department id. 理想情况下,休眠状态应使用最新部门ID更新员工。 Please let me know what could be missing here? 请让我知道这里可能缺少什么? Thanks. 谢谢。

Employee.java Employee.java

package com.empcatalogue.model;

import javax.persistence.CascadeType;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;

@Entity
public class Employee {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    private String name;

    @Embedded
    private Address address;

    @ManyToOne(cascade = CascadeType.MERGE)
    private Department department;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getId() {
        return id;
    }

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

    public Address getAddress() {
        return address;
    }

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

    public Department getDepartment() {
        return department;
    }

    public void setDepartment(Department department) {
        this.department = department;
    }
}

Department.java Department.java

package com.empcatalogue.model;

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.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;

@Entity
public class Department {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    private String name;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "department", fetch = FetchType.EAGER)
    private List<Employee> employees = new ArrayList<>();

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getId() {
        return id;
    }

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

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

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

}

EmployeeRepository.java EmployeeRepository.java

...
...
...    
public void addEmployee(Employee emp) {


    Session session = RepoManager.getSessionFactory().openSession();
        try {
            session.beginTransaction();

            session.save(emp);

            session.getTransaction().commit();
        } catch (Exception e) {
            session.getTransaction().rollback();
        } finally {
            session.close();
        }
    }

DepartmentRepository.java DepartmentRepository.java

...
...
...
    public void addDepartment(Department department) {
        Session session = RepoManager.getSessionFactory().openSession();
        try {
            session.beginTransaction();

            session.save(department);

            session.getTransaction().commit();
        } catch (Exception e) {
            session.getTransaction().rollback();
        } finally {
            session.close();
        }

    }

You're using javax.persistence package for your implementation, but you tagged your question as being Hibernate . 您正在使用javax.persistence包进行实现,但是您将问题标记为Hibernate Hibernate is just one of the implementations of the JPA (Java Persistence API). Hibernate只是JPA(Java Persistence API)的实现之一。 Even the Hibernate Web page recommends to use JPA. 甚至Hibernate Web页面也建议使用JPA。 Unless you're maintaining a legacy code, you better use JPA API to persist and fetch your entities. 除非维护旧版代码,否则最好使用JPA API持久化并获取您的实体。

Now to your question: 现在您的问题:

Now, I want to add a new department by associating an existing employee. 现在,我想通过关联现有员工来添加新部门。

To be able to persist as well as update your entities you should follow the following steps (code lines are just pseodo code): 为了能够持久并更新您的实体,您应该执行以下步骤(代码行仅是pseodo代码):

  • Create an instance of Department entity: 创建Department实体的实例:

     Department dept = new Department(); dept.setName(...); 
  • Fetch an existing Employee entity from the database within a transaction: 从事务中的数据库中获取现有的Employee实体:

     Employee emp = session.get(Employee.class, <employee_id_here>); 
  • Wire the entity instances together: 将实体实例连接在一起:

     dept.getEmployees().add(emp); emp.setDepartment(dept); 
  • Persist the employee: 坚持员工:

     session.save(dept); 

You should do all these in a transaction and everything should work as expected. 您应该在事务中进行所有这些操作,并且所有操作都应按预期进行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM