Search code examples
springspring-dataspring-data-jpajpql

How to update an object with another object value in JPQL using Spring JPA


I'm facing a problem in JPQL. I have two entities like below

class Employee{

  private Long id;
  private String name;
  private Department department;

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

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

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

  public Long getId(){
    return this.id;
  }

  public String getName(){
    return this.name;
  }

  public Department getDepartment(){
    return this.department;
  }
}

and...

class Department{

  private Long id;
  private String name;

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

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

  public Long getId(){
    return id;
  }

  public String getName(){
    return name;
  }
}

Now i need to update an Employee's department. I have tried the query below.

update Employee e set e.department.id = 'XXX' where e.id in (?1);

This is giving exception like

java.lang.IllegalStateException: org.hibernate.hql.internal.QueryExecutionRequestException: Not supported for DML operations.

Can you please guide me, How can i solve this issue?

Cheers, Teja.


Solution

  • In your Spring Data JPA repository interface do:

    interface EmployeeRepository extends Repository<Employee, Long> {
    
      @Modifying
      @Transactional
      @Query("update Employee e set e.department = ?2 where e = ?1")
      void updateDepartment(Employee employee, Department department);
    }
    

    Be sure to realize:

    • If you're executing modifying queries, you're bypassing lifecycle callbacks on the entities. This is a fundamental characteristic of JPA.
    • If you need lifecycle callbacks applied, load the Employee, manually set the Department, store the Employee.