How to update an object with another object value in JPQL using Spring JPA
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.
Employee
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.
2 Answers
2
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:
Employee
Department
Employee
@Modifying(clearAutomatically = true)
@Transactional
@Query("update Employee e set e.department = ?2 where e = ?1")
void updateDepartment(Employee employee, Department department);
@Modifying will separate it from select queries.
@Transactional will help transaction with the database.
@Query is the same old query execution.
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Thanks Oliver... U saved my time.
– Tej
Feb 4 '15 at 12:31