在JPA/JPQL的@Param @Query中使用对象而不是单个参数。

huangapple go评论102阅读模式
英文:

Using an object instead of single parameters in JPA/JPQL @Param @Query

问题

当进行查询时,您可以使用以下语法:

@Query(value = "SELECT v from DBTABLE v WHERE v.param1 = :param1 AND v.param2 = :param2")
List<Result> search(@Param("param1") String param1, @Param("param2") String param2)

如果我有超过2个参数怎么办?假设我有20个参数,是否有一种方法可以传递一个对象,并引用对象的属性呢?我的意思是这样的:

伪代码:

@Query(value = "SELECT v from DBTABLE v WHERE v.param1 = :#{#object.param1} AND v.param2 = :#{#object.param2}")
List<Result> search(@Param("object") SomeCustomObject object)

请注意,上述伪代码中的SomeCustomObject是您自定义的对象类型,您需要根据实际情况进行替换。

英文:

When doing querys you can do this syntax:

@Query(value = &quot;SELECT v from DBTABLE v WHERE v.param1 = param1 AND v.param2 = param2&quot;)
List&lt;Result&gt; search(@Param(&quot;param1&quot;) String param1, @Param(&quot;param2&quot;) String param2)

What if I had more then 2 parameters. Lets say I had 20 parameters, is there a way to give an object instead and refer to the object properties instead? What I mean is this:

Pseudocode:

@Query(value = &quot;SELECT v from DBTABLE v WHERE v.param1 = object.param1 AND v.param2 = object.param2&quot;)
List&lt;Result&gt; search(@Param(&quot;Object&quot;) SomeCustomObject object)

答案1

得分: 2

Spring Data JPA具有SpEL支持,可以访问查询方法的参数。这使您可以将参数简单地绑定为原样,或在绑定之前执行其他操作。

这使您可以编写如下的查询:

@Query("select u from User u where u.age = ?#{[0]}")
List<User> findUsersByAge(int age);

@Query("select u from User u where u.firstname = :#{#customer.firstname}")
List<User> findUsersByCustomersFirstname(@Param("customer") Customer customer);

更多详细信息,请参阅这里

英文:

Spring Data JPA has SpEL support that provides access to the query method arguments. This allows you to either simply bind the parameter as is or perform additional operations before binding.

This lets you write queries such as:

@Query(&quot;select u from User u where u.age = ?#{[0]}&quot;)
List&lt;User&gt; findUsersByAge(int age);

@Query(&quot;select u from User u where u.firstname = :#{#customer.firstname}&quot;)
List&lt;User&gt; findUsersByCustomersFirstname(@Param(&quot;customer&quot;) Customer customer);

For more details, see also

huangapple
  • 本文由 发表于 2023年7月27日 16:42:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76777968.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定