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

Use a dto as parameter in a native jpa query

我在 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 而不是多个参数?

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

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

With 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)