在本机jpa查询中使用dto作为参数



我在JPA中有以下查询,我想将EntityKey而不是多个参数传递给方法并在where子句中使用它:

@Query(value = "UPDATE #{#entityName} SET counter=counter+1 " +
"WHERE id1=:key.id1 AND id2=:key.id2", nativeQuery = true)
@Modifying
fun incrementCounter(@Param("key") key: EntityKey)

不幸的是,上面的代码不工作,我得到一个Named parameter not bound : key.id1异常。是否有可能在查询中传递和使用Dto而不是多个参数?

使用SpEL,您可以使用:#{#param.attribute}访问嵌套的参数属性,从而:

@Query(value = "UPDATE #{#entityName} SET counter=counter+1 " +
"WHERE id1=:#{#key.id1} AND id2=:#{#key.id2}")
@Modifying
fun incrementCounter(@Param("key") key: EntityKey)

一种选择是不使用本机查询:

@Query(value = "UPDATE MyEntity e SET e.counter=e.counter+1 " +
"WHERE e.id=:key")
@Modifying()
fun incrementCounter(@Param("key") key: EntityKey)

最新更新