使用可选的parameres更新查询

问题描述

我正在尝试使用可选参数更新行,但是在以下查询中出现错误

@Modifying
@Transactional
@Query("UPDATE Visit visits SET "
        + " visits.approvalStatus is null OR visits.approvalStatus = :approvalStatus "
        + ",visits.declineReason is null OR visits.declineReason =:declineReason "
        + " WHERE visits.visitId in :visitIds ")
public int patchUpdate(@Param("approvalStatus") String approvalStatus,@Param("declineReason") String declineReason,@Param("visitIds") List<Integer> visitIds);

错误日志:

Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: expecting EQ,found 'is' near line 1,column 69 [UPDATE com.quest.vms.entity.Visit visits SET  visits.approvalStatus is null OR visits.approvalStatus = :approvalStatus  WHERE visits.visitId in :visitIds ]

编辑以添加信息:在这里,我想在新数据不为null时更新特定字段,否则应忽略该参数。

感谢您的帮助

解决方法

is null用于检查该字段。 要根据条件设置列,可以使用:

UPDATE Visit visits SET "
        + "  visits.approvalStatus = CASE "
        + " WHEN visits.visitId in :visitIds THEN :approvalStatus "
        + " ELSE NULL "
        + " END"
,

UPDATE查询中存在语法错误,缺少用于设置字段值的部分。

可能使用COALESCE函数的查询(或使用IsNullNullIfNVL等函数的本机查询)可能会有所帮助:

@Query("UPDATE Visit visits SET "
     + "visits.approvalStatus = COALESCE(:approvalStatus,approvalStatus) "
     + "visits.declineReason = COALESCE(:declineReason,declineReason) "
     + " WHERE visits.visitId in :visitIds")
public int patchUpdate(
    @Param("approvalStatus") String approvalStatus,@Param("declineReason") String declineReason,@Param("visitIds") List<Integer> visitIds
);

或使用类似的CASE语句

@Query("UPDATE Visit visits SET "
     + "visits.approvalStatus = (CASE :approvalStatus WHEN NULL THEN approvalStatus ELSE :approvalStatus END) "
     + "visits.declineReason = (CASE :declineReason WHEN NULL THEN declineReason ELSE :declineReason END) "
     + " WHERE visits.visitId in :visitIds")
public int patchUpdate(
    @Param("approvalStatus") String approvalStatus,@Param("visitIds") List<Integer> visitIds
);
,

您可以在设置数据之类的同时添加案例条件

<ng-select 
  [items]="selection" 
  bindValue="id" 
  bindLabel="label" 
  [(ngModel)]="value" 
  (ngModelChange)="onChanges(value)">
</ng-select>

如果传递的值为null,则设置db中具有的值,同时设置传递的值。