问题背景
项目中有使用到Spring Data JPA来做查询,在某个查询中,想取同一个编码最新的那条,所以使用了limit函数,如下:
@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);