英文:
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 = "SELECT v from DBTABLE v WHERE v.param1 = param1 AND v.param2 = param2")
List<Result> search(@Param("param1") String param1, @Param("param2") 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 = "SELECT v from DBTABLE v WHERE v.param1 = object.param1 AND v.param2 = object.param2")
List<Result> search(@Param("Object") 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("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);
For more details, see also
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论