(記錄)JPA中使用@Query註解沒法使用limit函數的解決方法

問題背景

項目中有使用到Spring Data JPA來作查詢,在某個查詢中,想取同一個編碼最新的那條,因此使用了limit函數,以下:bash

@Query("select a from AclGrp a where a.grpcode = :grpcode order by gid desc limit 1")
public AclGrp findByGrpCode(@Param("grpcode") String grpcode);
複製代碼

但在實際測試中,發現limit函數無效,返回的仍是多個結果集,通過搜索發現,Spring Data JPA寫的SQL叫JPQL,不支持limit函數。函數

解決方法

在註解內增長參數nativeQuery,當加入nativeQuery參數時,@Query內的SQL是按原生SQL寫法來寫,limit函數生效,不加入nativeQuery參數則是JPQL,limit函數不生效。測試

@Query(nativeQuery=true, value = "select *a from Acl_Grp a where a.grpcode = :grpcode order by gid desc limit 1")
public AclGrp findByGrpCode(@Param("grpcode") String grpcode);
複製代碼
相關文章
相關標籤/搜索