【问题标题】:How to update an object with another object value in JPQL using Spring JPA如何使用 Spring JPA 在 JPQL 中使用另一个对象值更新对象
【发布时间】:2015-02-03 15:06:07
【问题描述】:

我在 JPQL 中遇到问题。我有两个像下面这样的实体

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

还有……

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 的部门。我试过下面的查询。

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.

你能指导我吗,我该如何解决这个问题?

干杯, 泰迦。

【问题讨论】:

    标签: spring spring-data spring-data-jpa jpql


    【解决方案1】:

    在您的 Spring Data 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

    【讨论】:

    • 谢谢奥利弗...你节省了我的时间。
    【解决方案2】:
    @Modifying(clearAutomatically = true) 
    @Transactional
    @Query("update Employee e set e.department = ?2 where e = ?1")
    void updateDepartment(Employee employee, Department department);
    

    @Modifying 会将其与选择查询分开。

    @Transactional 将帮助与数据库进行事务。

    @Query 是相同的旧查询执行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-05
      • 2018-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-25
      相关资源
      最近更新 更多