我正在努力使订单参数化。最好的办法就是
... order by :orderColumn :orderDirection ...有没有可能转到:
@Query("select * from Document where folderId = :folderId AND documentType = :documentType"
+ " order by created desc limit :limit")
List<Document> findByFolderIdAndDocumentTypeOrderByWithLimit(Long folderId, String documentType,
String orderColumn, Integer limit);进入:
@Query("select * from Document where folderId = :folderId AND documentType = :documentType"
+ " order by :orderColumn desc limit :limit")
List<Document> findByFolderIdAndDocumentTypeOrderByWithLimit(Long folderId, String documentType,
String orderColumn, Integer limit);我使用spring-data-jdbc 1.1.3.REELASE版本。即使只是为了列名这样做也会对我有很大的帮助。
发布于 2020-02-23 19:45:08
使用PagingAndSortingRepository
@Query("select * from Document where folderId = :folderId AND documentType = :documentType")
List<Document> findByFolderIdAndDocumentTypeOrderByWithLimit(Long folderId, String documentType, Pageable pageable);并调用该方法:
findByFolderIdAndDocumentTypeOrderByWithLimit(1,"Type", PageRequest.of(0, <limit>, Sort.by(<column name>).descending());例如,您可以对here进行优化
发布于 2020-02-24 14:44:46
用绑定参数替换列名是不可能的。这是JDBC的限制,甚至可能是SQL的限制。
您可以做的是使用一个表达式,该表达式根据绑定参数计算出不同列的值。就像这样
... ORDER BY CASE
WHEN :orderColumn = 'created' THEN created
WHEN :orderColumn = 'updated' THEN updated
WHEN :orderColumn = 'deleted' THEN deleted
ELSE 1
END;请注意,查询优化器不能很好地支持这种构造,因此不会使用任何可能适用的索引。
如果您需要优化器提供更好的支持,您始终可以编写动态创建的自定义查询。如果您决定这样做,请确保没有将来自不受信任来源的字符串合并到SQL语句中,以避免SQL注入漏洞。
发布于 2020-03-13 18:37:01
在出现支持可分页对象的spring-data-jdbc版本(据我所知是2.X.X.RELEASE)之前,我已经决定在这种特殊情况下使用NamedParameterJdbcTemplate并结束我自己的查询。我希望这篇文章或其他答案能对某些人有所帮助。感谢您的帮助:)
https://stackoverflow.com/questions/60361743
复制相似问题