JPA--单表操作二、(条件查询、统计查询、排序查询、分组查询、分页查询)

SpringBoot集成Jpa对数据进行排序、分页、条件查询和过滤 NotIn:等价于 SQL 中的 "not in",findByNameNotIn(Collection userList) ,方法的参数可以是 Collection 类型,也可以是数组或者不定长参数;In:等价于 SQL 中的 "in",findByIdIn(Collection userIdList) ,方法的参数可以是 Collection 类型,也可以是数组或者不定长参数;也可以使用findAllBy。JPA为我们提供了分页的方法,我们可以查看接口集成的JpaRepository接口的关系图。 阅读详情

单表操作

表与数据与上篇相同,点击跳转

条件查询

占位符
JPQL 语句支持两种方式的参数定义方式 : 命名参数和位置参数 。 在同一个查询语句中只允许使用一种参数定义方式。

  • 位置参数:“ ?+ 位置编号”
  • 命名参数:“ : + 参数名”

位置参数

@Test
public void selectByTest(){
    EntityManager entityManager = JpaUtils.getEntityManager();
    EntityTransaction transaction = entityManager.getTransaction();
    transaction.begin();

    String spql = "from Customer where custName = ?1";
    Query query = entityManager.createQuery(spql);
    //设置参数
    query.setParameter(1, "万达");
    Object singleResult = query.getSingleResult();
    System.out.println(singleResult);

    transaction.commit();
    entityManager.close();
}

控制台打印:

Hibernate: select customer0_.cust_id as cust_id1_0_, customer0_.cust_address as cust_add2_0_, customer0_.cust_industry as cust_ind3_0_, customer0_.cust_level as cust_lev4_0_, customer0_.cust_name as cust_nam5_0_, customer0_.cust_phone as cust_pho6_0_, customer0_.cust_source as cust_sou7_0_ from cst_customer customer0_ where customer0_.cust_name=?
Customer{custId=3, custName='万达', custSource='null', custIndustry='房地产', custLevel='三', custAddress='大连', custPhone='33333333'}

命名参数

@Test
public void selectByTest(){
    EntityManager entityManager = JpaUtils.getEntityManager();
    EntityTransaction transaction = entityManager.getTransaction();
    transaction.begin();

    String spql = "from Customer where custAddress = :address";
    Query query = entityManager.createQuery(spql);
    //设置参数
    query.setParameter("address", "广州");
    List resultList = query.getResultList();
    for(Object o : resultList)
        System.out.println(o);

    transaction.commit();
    entityManager.close();
}

控制台打印:

Hibernate: select customer0_.cust_id as cust_id1_0_, customer0_.cust_address as cust_add2_0_, customer0_.cust_industry as cust_ind3_0_, customer0_.cust_level as cust_lev4_0_, customer0_.cust_name as cust_nam5_0_, customer0_.cust_phone as cust_pho6_0_, customer0_.cust_source as cust_sou7_0_ from cst_customer customer0_ where customer0_.cust_address=?
Customer{custId=4, custName='恒大', custSource='null', custIndustry='矿泉水', custLevel='四', custAddress='广州', custPhone='44444444'}
Customer{custId=5, custName='网易', custSource='null', custIndustry='游戏', custLevel='五', custAddress='广州', custPhone='55555555'}

统计查询

  • 聚集函数
    查询可以返回作用于属性之上的聚集函数的计算结果:
    受支持的聚集函数如下:
    avg(…), sum(…), min(…), max(…)
    count(*)
    count(…), count(distinct…), count(all…)
    可以选择子句中使用数学操作符、连接以及经过验证的SQL函数:
    关键字distinct 与 all 也可以使用,它们具有与SQL相同的语义。
@Test
public void selectCountTest(){
    EntityManager entityManager = JpaUtils.getEntityManager();
    EntityTransaction transaction = entityManager.getTransaction();
    transaction.begin();

    String jpql1 = "select count(*) from pers.zhang.domain.Customer";
    String jpql2 = "select sum(custId) from pers.zhang.domain.Customer";
    String jpql3 = "select avg(custId) from pers.zhang.domain.Customer";
    String jpql4 = "select max(custId) from pers.zhang.domain.Customer";
    String jpql5 = "select min(custId) from pers.zhang.domain.Customer";

    Query query1 = entityManager.createQuery(jpql1);
    Query query2 = entityManager.createQuery(jpql2);
    Query query3 = entityManager.createQuery(jpql3);
    Query query4 = entityManager.createQuery(jpql4);
    Query query5 = entityManager.createQuery(jpql5);

    Object singleResult1 = query1.getSingleResult();
    Object singleResult2 = query2.getSingleResult();
    Object singleResult3 = query3.getSingleResult();
    Object singleResult4 = query4.getSingleResult();
    Object singleResult5 = query5.getSingleResult();

    System.out.println(singleResult1);
    System.out.println(singleResult2);
    System.out.println(singleResult3);
    System.out.println(singleResult4);
    System.out.println(singleResult5);

    transaction.commit();
    entityManager.close();
}

控制台打印:

Hibernate: select count(*) as col_0_0_ from cst_customer customer0_
Hibernate: select sum(customer0_.cust_id) as col_0_0_ from cst_customer customer0_
Hibernate: select avg(customer0_.cust_id) as col_0_0_ from cst_customer customer0_
Hibernate: select max(customer0_.cust_id) as col_0_0_ from cst_customer customer0_
Hibernate: select min(customer0_.cust_id) as col_0_0_ from cst_customer customer0_
5
15
3.0
5
1

排序查询

@Test
public void selectByOrderTest(){
    EntityManager entityManager = JpaUtils.getEntityManager();
    EntityTransaction transaction = entityManager.getTransaction();
    transaction.begin();

    String spql = "from Customer order by custId desc";
    Query query = entityManager.createQuery(spql);
    //设置参数
    List resultList = query.getResultList();
    for(Object o : resultList)
        System.out.println(o);

    transaction.commit();
    entityManager.close();
}

控制台打印:

Hibernate: select customer0_.cust_id as cust_id1_0_, customer0_.cust_address as cust_add2_0_, customer0_.cust_industry as cust_ind3_0_, customer0_.cust_level as cust_lev4_0_, customer0_.cust_name as cust_nam5_0_, customer0_.cust_phone as cust_pho6_0_, customer0_.cust_source as cust_sou7_0_ from cst_customer customer0_ order by customer0_.cust_id desc
Customer{custId=5, custName='网易', custSource='null', custIndustry='游戏', custLevel='五', custAddress='广州', custPhone='55555555'}
Customer{custId=4, custName='恒大', custSource='null', custIndustry='矿泉水', custLevel='四', custAddress='广州', custPhone='44444444'}
Customer{custId=3, custName='万达', custSource='null', custIndustry='房地产', custLevel='三', custAddress='大连', custPhone='33333333'}
Customer{custId=2, custName='腾讯', custSource='null', custIndustry='互联网', custLevel='二', custAddress='深圳', custPhone='22222222'}
Customer{custId=1, custName='阿里巴巴', custSource='修改后的', custIndustry='电商', custLevel='一', custAddress='杭州', custPhone='11111111'}

分组查询

@Test
public void selectByGroupTest(){
    EntityManager entityManager = JpaUtils.getEntityManager();
    EntityTransaction transaction = entityManager.getTransaction();
    transaction.begin();

    String spql = "select custLevel,count(*) from Customer group by custLevel";
    Query query = entityManager.createQuery(spql);
    //设置参数
    List<Object> resultList = query.getResultList();
    System.out.println("登记:个数");
    for(Object o : resultList){
        Object[] objs = (Object[])o;
        System.out.println(objs[0] + ":" + objs[1]);
    }

    transaction.commit();
    entityManager.close();
}

控制台打印:

Hibernate: select customer0_.cust_level as col_0_0_, count(*) as col_1_0_ from cst_customer customer0_ group by customer0_.cust_level
登记:个数
一:1
三:1
二:1
五:1
四:1

分页查询

JPQL的分页查询与MySql的limit十分相似,使用两个方法:

  • query.setFirstResult(arg),设置第一条结果从哪个索引开始,相当于limit中的第一个?。
  • query.setMaxResults(arg),设置一次查询多少条数据,相遇于limit中的第二个?。
@Test
public void selectPageTest(){
    EntityManager entityManager = JpaUtils.getEntityManager();
    EntityTransaction transaction = entityManager.getTransaction();
    transaction.begin();

    String spql = "from Customer";
    Query query = entityManager.createQuery(spql);
    //设置参数
    query.setFirstResult(0);
    query.setMaxResults(2);

    List resultList = query.getResultList();
    for(Object o : resultList)
        System.out.println(o);

    transaction.commit();
    entityManager.close();
}

控制台打印:

Hibernate: select customer0_.cust_id as cust_id1_0_, customer0_.cust_address as cust_add2_0_, customer0_.cust_industry as cust_ind3_0_, customer0_.cust_level as cust_lev4_0_, customer0_.cust_name as cust_nam5_0_, customer0_.cust_phone as cust_pho6_0_, customer0_.cust_source as cust_sou7_0_ from cst_customer customer0_ limit ?
Customer{custId=1, custName='阿里巴巴', custSource='修改后的', custIndustry='电商', custLevel='一', custAddress='杭州', custPhone='11111111'}
Customer{custId=2, custName='腾讯', custSource='null', custIndustry='互联网', custLevel='二', custAddress='深圳', custPhone='22222222'}
JPA多条件分页分组查询 排序,多条件查詢 直接上實現代碼 @Override public Page<VaccineSuggests> searchByCondition(Date startTime, Date endTime, Long regionId, String orgName,String reg, Integer cp, Integer ps) { // 排序规则,此处排序可以添加集合 Sort.Order order = new Sort.Order(Sort. 阅读详情

相关推荐

MyBatis-Plus Lambda聚合查询:类型安全的统计报表开发实践

在Java后端开发中,聚合查询是处理数据统计与报表分析的核心技术,它通过COUNT、SUM、AVG等函数对数据进行摘要计算。其原理是将数据库中的原始记录按需分组并应用聚合函数,最终提炼出有价值的业务摘要信息。这项技术的价值在于能够高效地从海量数据中获取关键指标,避免在应用层进行繁琐且低效的数据遍历与计算。典型的应用场景包括用户行为分析、销售数据看板、运营统计报表等各类需要数据汇总的业务模块。随着ORM框架的发展,开发者对类型安全和编码体验提出了更高要求。MyBatis-Plus框架的Lambda聚合查询功能

weixin_30240349的博客 371

JPA分组查询统计

JPA分组查询统计count List professionUserList = jpaQueryFactory.select(Projections.bean( DtoProfessionUser.class, QYjUser.yjUser.profId, QYjUser.yjUser.count().as(“count”))) .from(QYjUser.yjUser) .groupBy(QYjUser.yjUser.profId).fetch();

qq_38427272的博客 2721

莆田市C++专项选拔第一轮题4

现在小明同学想要从两堆硬币中各选择一枚硬币,使得两枚硬币的面值之和 不超过 k。不同的硬币组合,就算面值相同,也视为不同的方案。现在他把这些硬币分成了两堆,已知两堆硬币分别有 n 和 m 枚硬币。可选方案有: (1,2), (1,1), (1,1), (5,2), (5,1), (5,1),共 6 种。第一行三个整数 n, m, k,分别表示第一堆硬币的数量,第二堆硬币的数量,以及面值之和的上限。对于30%的数据,1 ≤ n , m ≤ 1000 , 1 ≤ b , c ≤ 1000。

lpstudio的博客 925

JAVA JPA 根据指定时间格式进行日期分组统计

JPA 根据指定时间格式进行日期分组统计

qq_51177455的博客 1076

解决西门子Step 7 basic 找不到许可证问题

你在使用博图软件是否遇到过Step 7 basic 找不到许可证的问题呢!不言怕,今天我就来告诉你该如何处理吧!看步骤: 1.删除原授权的License: 打开Automation License Manager应用,然后我们可以发现仅有的License Key前面有一个时钟,说明它已经过期不可用,我们就要去寻求新的Key. 打开“我的电脑”,选择C盘,点击上方查看 点击选项–>查看 然...

让技术没有门槛 14万+

Dify使用教程(创建应用)

Dify的安装部署我已经写过了,简单的模型配置我也在前面进行了讲解,今天我们主要来讲讲如何使用Dify。

wal1314520的博客 1万+

使用jpa实现数据的查找

一、什么是jpa JPA本身不是一个工具或框架; 相反,它定义了一组可以由任何工具或框架实现的概念。虽然JPA的对象关系映射(ORM)模型最初基于Hibernate,但它已经发展了。简单来说,JPA只是一个简化对象关系映射来管理Java应用程序中的关系数据的规范。 它提供了一个平台,可以直接使用对象而不是使用SQL语句。 二、什么是Hibernate Hibernate是一个开放源代码的对象关系映射框架,它对JDBC进行了非常轻量级的对象封装,是一个全自动的ORM框架,它可以自动生成SQL语句,自动执

m0_74067323的博客 6030

芯片详解——AD7606

AD7606详解

weixin_45661757的博客 5021

Java,如何使用spring data JPA完成分组查询?“曲线救国”,提升效率,代码优化

销售单,查询某时间范围内的,门店id集合中的数据,并对数据进行分组,对分组后的数据进行合并,等计算。算总账等数据分析,使用这个方法可以获得任何sql查询表的数据。

m0_72405471的博客 1574

Flutter UI代码生成实战:Cursor与MCP的企业级规范适配

本文探讨了在企业级Flutter项目中,如何通过配置Cursor Rules与定制Figma MCP工具,为AI代码生成设定严格的开发规范。该方法解决了AI生成代码与现有项目架构、命名约定及资源引用规范脱节的核心痛点,实现了从Figma设计稿到高质量、可维护Flutter UI代码的自动化流程,显著提升团队协作效率与代码一致性。

http9protocoller的博客 280

Livox MID360与Fast-LIO2的实战部署指南:从驱动安装到点云处理

本文提供Livox MID360激光雷达与Fast-LIO2激光惯性里程计从零开始的实战部署指南。详细介绍了Ubuntu系统下的驱动安装、网络配置、点云数据验证以及Fast-LIO2算法的编译、参数配置与联合启动流程,帮助开发者快速搭建移动机器人SLAM系统,并包含关键参数调优与常见故障排查方法。

java5的博客 1024

JPA分组查询,求和,自定义查询字段,自定义VO承接

一.JPA使用过程中的问题 JPA常用的查询方法,用实体对应的repository的执行find方法,查询都是实体的全部字段或者其中的单个字段。 如果对一个字段进行分组查询时,会出现问题,这里分享一个自定义查询方法。 二.解决问题 一.分组查询 表数据 JPA对应实体 结果集VO...

乐闻世界 1万+

基于STM32、HAL库的TCA9555PWR I/O扩展器驱动程序设计

define TCA9555_ADDR_BASE 0x20 // 基础地址 (A0=A1=A2=0)* @param direction: 方向 (0=输出, 1=输入)* @param direction: 方向 (0=输出, 1=输入)* @param polarity: 极性 (0=正常, 1=反转)* @param polarity: 极性 (0=正常, 1=反转)

corlin6688的博客 527

jpa中分组统计分页查询

public PageDTO findSettlementReport(SettlementRequestBody request){ String activityId = request.getActivityId(); //这是因为我再查询的时候是根据活动id进行查询的 需要在返回 这样在翻页的时候才不会重置查询结果 //criteriaBuilder用于构建CriteriaQuery的构建器对象 CriteriaBuilder criteriaBuilder = e

weixin_50093663的博客 2127

Transformer模型详解

​本文主要介绍Transformer系列,从基础到理论,对注意力机制进行总结并解释《Attention is all you need》,提出解决sequence to sequence问题的transformer模型,用全attention的结构代替了lstm,抛弃了之前传统的encoder-decoder模型必须结合cnn或者rnn的固有模式,只用attention。文章的主要目的是在减少计算量和提高并行效率的同时不损害最终的实验结果。

专注大数据与人工智能技术分享,欢迎私信加群互相学习! 5295

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

详解Jpa动态复杂条件查询,查询指定字段、并包括sum、count、avg等数学运算,包括groupBy分组

Jpa是我一直推荐在Springboot及微服务项目中使用的数据库框架,并由于官方的并不是十分友好和易用的api,导致很多人使用起来并不方便,下面就来展示一下我对api进行了封装后的代码。大大减轻了使用难度。 效果展示 首先我们直接来看最终的结果: 譬如有个entity叫PtActivity,它有一个Repository。 public interface PtActivityRepos...

tianyaleixiaowu的专栏 2万+

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

JPA 多条件(包括时间)统计查询

几种写法关键代码: 这个与使用@Query 类似: Query query = entityManager.createQuery("SELECT new com.test.OperationStatisticItem( count(pl),function('date_format',pl.createdTime,'%Y-%m-%d') ,pl.action,pl.operator) from ProjectLogInfoEntity pl " + "wh

u011562187的专栏 2018

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

SpringData Jpa中count的使用

通常,我们会有统计数量的需求,Jpa对一些简单统计数量的需求通过方法名就可以解析。然而对于稍微复杂的需求则无法通过方法名解析。 对于这种需求,还是需要写sql实现。 1、默认提供的count() 当我的Repository接口继承JpaRepository时,默认会继承它的一个count()方法 @Repository public interface StudentReposito...

ununie的博客 2万+

JPA查询-3种查询方式

spring data jpa

没有伞的孩子必须努力奔跑!—小林 6117

JPA查询方法

JPA默认查询方法 findOne(id):查询指定id的数据 List findAll():查询对应实体的所有数据 List findAll(Sort sort):带排序的查询 Sort(Direction.DESC,String properties),Direction指定排序方式,properties指定排序的字段 Sort(Direction direction, List pro...

hy1255564202的博客 3001

【JPA】SpringBoot JPA 使用GroupBy 进行分组查询

转自https://blog.youkuaiyun.com/winnershili/article/details/80695218 首先建立一个实体 装数据用 public class OrderGoods { private Goods goods; private Integer year = 0; //年份 private Integ...

mudarn的博客 1万+

SpringDataJPA--查询方式

Spring Data JPA的查询方式 4.1 使用Spring Data JPA中接口定义的方法进行查询 在继承JpaRepository,和JpaRepository接口后,我们就可以使用接口中定义的方法进行查询 继承JpaRepository后的方法列表 继承JpaSpecificationExecutor的方法列表 测试count()方法和exists()方法 /** * 测试统计查询: 查询客户的总数量 * count():通过主键id进行统计客户总数量 *

qq_43404873的博客 974

JPA使用CriteriaQuery实现动态分组查询

JPA中实现动态分组查询,即输入几个筛选参数就按照几个参数进行分组查询,但是不知道输入的是几个参数,要实现动态的分组查询,用CriteriaQuery实现。

dames的博客 1039

使用SpringDateJPA用@Query写的原生sql分组聚合查询遇到的坑

使用SpringDateJPA用@Query写的原生sql分组聚合查询遇到的坑

m0_47671062的博客 786

Spring JPA 实现slecet count(*) group by

@Repository public interface AAARepository extends JpaRepository<LoginLog, Long>, QuerydslPredicateExecutor { @Query("select new com.xxx.AAA(b.account,count(*)) from BBB b where b.createdDate BE...

菜鸟很菜的专栏 6437

一篇文章带你搞定 JPA 中的复杂查询(JPQL)

前面我们已经学习了:一篇文章带你搞定如何使用 Jpa 完成数据库的增删改操作 学会了 JPA 的基础操作,本篇文章将向大家讲述 JPA 中的复杂查询操作

南淮北安的博客 3847
上一篇: JPA--单表操作示例一、(增删改查)
下一篇: JPA--SpringData JPA环境搭建及简单操作
吴声子夜歌
博客等级 码龄9年 2687粉丝 2267原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值