(记录)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);
复制代码
相关文章
相关标签/搜索