1

How to update only the entity attributes passed from @RequestBody using Spring Rest Controller and Spring Data JPA ?

Employee Entity:

@Entity
@Table(name = "employee")
@DynamicUpdate
public class Employee {
    @Id
    @Column(name = "employee_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer employeeId;

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

    @Column(name = "employee_desgn")
    private String employeeDesgn;

    @Column(name = "employee_email")
    private String employeeEmail;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "company_id", referencedColumnName = "company_id")
    private Company company;
}

Service Class Method:

public Employee updateEmployee(Employee employee) {
    return employeeRepository.save(employee);
}

RequestBody:

{
    "employeeId":4,
    "employeeName":"Paul",
    "employeeDesgn":"Lead"
}

Hibernate Update Query:

update employee set company_id=?, employee_desgn=?, employee_name=? where employee_id=?

Spring Data JPA is trying to set company_id as null to update even though I am not passing it through RequestBody ? But if I got entity from database using employee_id passed and then if I tried to save() then its working fine.

I would like to update only entity attributes which are passed through Request Body. How to handle this scenario ?

Krish
  • 1,804
  • 7
  • 37
  • 65

2 Answers2

1

In another question i proposed a solution using BeanUtils of apache commons :

public class NullAwareBeanUtilsBean extends BeanUtilsBean {
    @Override
    public void copyProperty(Object dest, String name, Object value) throws IllegalAccessException, InvocationTargetException {
        if (value == null)
            return;
        super.copyProperty(dest, name, value);
    }
}

You can update your object with :

BeanUtilsBean notNull = new NullAwareBeanUtilsBean();
notNull.copyProperties(destObj, origObj);

Here is my original answer

zpavel
  • 951
  • 5
  • 11
0

you can find the employee by id and only populate those values. An Example below.

public Employee updateEmployee(Employee employee) {
    Employee emp = employeeRepository.findOne(employee.getEmployeeId());

    emp.setEmployeeName(employee.getEmployeeName());
    emp.setEmployeeDesgn(employee.getEmployeeDesgn());

    employeeRepository.save(emp);
}

only employee name and employee desgn will be change.

Jorge L. Morla
  • 630
  • 5
  • 14