在 JPA 查询中,我可以通过 属性 和 DESC/ASC 顺序作为方法签名中的参数传递吗?
In JPA Query, can I pass the order by property and DESC/ASC order as parameters in the method signature?
我正在使用 spring 框架和工作存储库级别的实现。
我有一个 class:
@Repository
public interface MyClassReadRepository extends ReadRepository<MyClass, Integer>
在这个class中有一个看起来像这样的方法:
@Query("SELECT a FROM MyClass a WHERE a.type IN :myType ORDER BY :someProperty :someOrder")
Page<MyClass> findByTypeAndOrder(@Param("myType") List<MyType> myType, @Param("someProperty")String someProperty, @Param("someOrder")String someOrder, Pageable pageable)
但显然查询结构是错误的:“:someProperty”应该是一个标识符...
我的问题是:上面例子中order和sort参数如何传递?
提前致谢!
My question is: how to pass order and sort parameters in the example above?
在 JPA(和 JDBC)中,参数是 values 的占位符,而不是更通用的查询文本。您不能使用它们代替标识符,例如列或 table 名称,也不能代替关键字,例如 ASC
/ DESC
.
形式相似但一个或多个标识符或关键字不同的查询是根本不同的查询。您需要不同的 Query
来表示它们。
您已经在传递 Pageable 对象。您可以按如下方式传递您的参数
new PageRequest(1, 10, Sort.Direction.ASC, "yourProperty");
使用:
PageRequest(page, size, direction, properties)
创建一个应用了排序参数的新 PageRequest。
参数:
page:从零开始的页面索引。 (例如 5 或 10 等)
size:返回页面的大小。 (例如 50 或 100 等)
direction:指定排序的方向,可以为空。 (喜欢Sort.Direction.ASC)
properties:排序依据的属性,不能为空。 (喜欢 "my column name")
我正在使用 spring 框架和工作存储库级别的实现。
我有一个 class:
@Repository
public interface MyClassReadRepository extends ReadRepository<MyClass, Integer>
在这个class中有一个看起来像这样的方法:
@Query("SELECT a FROM MyClass a WHERE a.type IN :myType ORDER BY :someProperty :someOrder")
Page<MyClass> findByTypeAndOrder(@Param("myType") List<MyType> myType, @Param("someProperty")String someProperty, @Param("someOrder")String someOrder, Pageable pageable)
但显然查询结构是错误的:“:someProperty”应该是一个标识符...
我的问题是:上面例子中order和sort参数如何传递?
提前致谢!
My question is: how to pass order and sort parameters in the example above?
在 JPA(和 JDBC)中,参数是 values 的占位符,而不是更通用的查询文本。您不能使用它们代替标识符,例如列或 table 名称,也不能代替关键字,例如 ASC
/ DESC
.
形式相似但一个或多个标识符或关键字不同的查询是根本不同的查询。您需要不同的 Query
来表示它们。
您已经在传递 Pageable 对象。您可以按如下方式传递您的参数
new PageRequest(1, 10, Sort.Direction.ASC, "yourProperty");
使用:
PageRequest(page, size, direction, properties)
创建一个应用了排序参数的新 PageRequest。 参数:
page:从零开始的页面索引。 (例如 5 或 10 等)
size:返回页面的大小。 (例如 50 或 100 等)
direction:指定排序的方向,可以为空。 (喜欢Sort.Direction.ASC)
properties:排序依据的属性,不能为空。 (喜欢 "my column name")