SpringJPA实现count(*) 使用SpringJPA 直接实现count(*)

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

SpringJPA实现count(*) 使用SpringJPA 直接实现count(*)

hikeboy   2021-11-29 我要评论
想了解使用SpringJPA 直接实现count(*)的相关内容吗,hikeboy在本文为您仔细讲解SpringJPA实现count(*)的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点: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);

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

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

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们