怎么使用SpringJPA实现count(*)

2023-05-13,,

这篇文章主要介绍“怎么使用SpringJPA实现count(*)”,在日常操作中,相信很多人在怎么使用SpringJPA实现count(*)问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”怎么使用SpringJPA实现count(*)”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

    SpringJPA 直接实现count(*)

    刚开始使用JPA时,基本都依赖@query(SQL)注解通过原生sql来实现

    根据编号统计条数:

    方法一

    @Query(" select count(t) from FollowerInfo t where investUserId = :invUserId")
        Integer findFollowerNumberByInvUserId(@Param("invUserId") Long invUserId);

    这种原生的方式,跟直接写SQL没什么区别。虽然能实现功能,但是浪费了JPA的简洁简化代码的设计的优点。

    网上看到另外一个方法:

    List findAll(Specification spec);

    在repository层findAll,然后在service层封装,获取list.size()来处理总条数问题。

    这样避免了写SQL语句。

    今天看了一下CrudRepository的源码 发现该接口源码里面有一个函数:

    方法二

    /**
         * Returns the number of entities available.
         * 
         * @return the number of entities
         */
        long count();

    于是继承了CrudRepository 写了一个demo:

    方法三

    Long countByInvestUserId(Long investUserId);

    一行代码就全部搞定! 效果跟方法1一样

    (spring data jpa)jpa中使用count计数方法

    spring data jpa中使用count计数方法很简单

    直接在dao层写方法即可

    int countByUidAndTenementId(String parentUid, String tenementId);

    到此,关于“怎么使用SpringJPA实现count(*)”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注本站网站,小编会继续努力为大家带来更多实用的文章!

    《怎么使用SpringJPA实现count(*).doc》

    下载本文的Word格式文档,以方便收藏与打印。