使用SpringJPA 直接实现count(*)

来自:网络
时间:2021-11-29
阅读:
目录

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);

这样即可根据传入的字段查询即可。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

返回顶部
顶部