[英]Parametrised order in spring-data-jdbc
我正在努力使訂單參數化。 最好是有
... 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 版本。 即使只為列名做這件事也會對我有很大幫助。
使用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());
舉個例子,你可以在這里罰款
用綁定參數替換列名是不可能的。 這是 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 注入漏洞。
在有支持 Pagable 對象的spring-data-jdbc
(據我所知 2.XXRELEASE)之前,我已經決定針對這種特殊情況使用NamedParameterJdbcTemplate
並NamedParameterJdbcTemplate
我自己的查詢。 我希望這里的這個或其他答案會對某人有所幫助。 感謝您的幫助 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.