2015-02-03 4 views
1

JPQL에서 문제가 있습니다. 나는 JPQL에서 Spring을 사용하여 다른 객체 값으로 객체를 업데이트하는 방법 JPA

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; 
    } 
} 

지금 내가 Employee의 부서를 업데이트해야합니다 ...이 아래

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; 
    } 
} 

같은 엔티티와 있습니다. 나는 아래의 쿼리를 시도했다.

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

내가이 문제를 해결할 수있는 방법

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

당신이 나를 인도시겠습니까 같은이주고 예외?

건배, 테자.

답변

1

당신의 스프링 데이터 JPA 저장소 인터페이스에서 수행

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); 
} 

것은 실현하십시오 :

  • 수정 쿼리를 실행하는 경우 엔티티에서 수명주기 콜백을 건너 뜁니다. 이것이 JPA의 근본적인 특징입니다.
  • 라이프 사이클 콜백이 적용되어야하는 경우 Employee을로드하고 Department을 수동으로 설정하고 Employee을 저장합니다.
+1

감사합니다 올리버 ... U는 내 시간을 저장했습니다. – Tej

0

이처럼 시도 (대신 ID를 전달하는 개체를 전달할 수) :

Query query = em.createQuery("UPDATE Employee e set e.department=:dep where e=:employee"); 
query.setParameter("dep", departement); 
//You should have first yourEmployee 
query.setParameter("employee",yourEmployee); 
int updateCount = em.executeUpdate(); 
+0

이 아닌 하나 하나에 대해 * 모든 * 직원의 부서를 설정하는 것입니다. 또한 Spring Data JPA가 아닌 원시 JPA에 있습니다. –

+0

@OliverGierke 고정 –

0

먼저 세션 된 employee 개체를 가져온 다음 업데이트 할 개체를 설정해야합니다. 이렇게하십시오.

@Transactional 
void updateDepartment(Employee employee, Department department){ 
    Employee sessionedEmployee = em.find(Employee.class, employee.getId()); 
    Department sessionedDepartment=em.find(Department .class,department.getId()); 
    sessionedEmployee.setDepartment(sessionedDepartment); 

}