spring-data-jpa 将参数传递到@Query注解

72qzrwbm  于 2022-11-10  发布在  Spring
关注(0)|答案(1)|浏览(259)

我尝试使用带参数的@Query注解,但我无法在线找到很多示例,并且不断收到错误:

Could not locate named parameter [port], expecting one of [port%, user.id%]; nested exception is java.lang.IllegalArgumentException: Could not locate named parameter [port], expecting one of [port%, user.id%]

我的实现:

@Query(value = "UPDATE Port SET active=FALSE, port_id=%:user.id%, expiration=NOW()+ INTERVAL 5 MINUTE  WHERE port=%:port%", nativeQuery = true)
void setInUse(@Param("user") User user, @Param("port") int port);
aiazj4mn

aiazj4mn1#

这实际上是文档化的. Baeldung has an article about it,您可以通过搜索“@Query JPA”找到它。
位置

@Query("SELECT e FROM Entity e WHERE e.property = ?1")
Entity getElement(Integer param);

@Query("SELECT * FROM entity WHERE property = ?1", nativeQuery = true)
Entity getElementNative(Integer param);

已命名

@Query("SELECT e FROM Entity e WHERE e.property = :param ")
Entity getElement(@Param("param") Integer param);

@Query("SELECT * FROM entity WHERE property = :param ", nativeQuery = true)
Entity getElement(@Param("param") Integer param);

There is another way that allows you to access properties的对象,如数组、Map,甚至是另一个实体或POJO。

/* positional */
@Query("SELECT e FROM Entity e WHERE e.property = ?#{[0].property} ")
Entity getElement(OtherEntity param);

@Query("SELECT * FROM entity WHERE property = ?#{[0].property} ", nativeQuery = true)
Entity getElement(OtherEntity param);

/* named */
@Query("SELECT e FROM Entity e WHERE e.property = :#{#param.property}")
Entity getElement(@Param("param") OtherEntity param);

@Query("SELECT * FROM entity WHERE property = :#{#param.property} ", nativeQuery = true)
Entity getElement(@Param("param") OtherEntity param);

/*  SpEL, works in native and JPQL queryies */

/* for arrays */
@Query("SELECT e FROM Entity e WHERE e.property = ?#{[0][0]} ")
Entity getElement(Integer[] param);

@Query("SELECT e FROM Entity e WHERE e.property = :#{#param[0]}")
Entity getElement(@Param("param") Integer[] param);

/* for maps */
@Query("SELECT e FROM Entity e WHERE e.property = ?#{[0]['property']} ")
Entity getElement(Map<String, Object> param);

@Query("SELECT e FROM Entity e WHERE e.property = :#{#param['property']}")
Entity getElement(@Param("param") Map<String, Object> param);

相关问题