Spring Data Querydsl-JPA 的简单入门笔记

  • 一、 Querydsl面试常识问题
    • 1.Querydsl是什么?
  • 二、简单项目使用
    • 1.pom依赖
    • 2.新增插件,自动生成Q版实体类:
    • 3.JPAQueryFactory配置:
    • 4.新建po实体
    • 5.使用 compile编译建立Q版对象
    • 6.简单操作-用法:
      • 6.1. 注入 JPAQueryFactory
      • 6.2. 条件查询
      • 6.3. 模糊查询并排序
      • 6.4. 区间用法(between)
      • 6.5. 分页查询
      • 6.6. in查询
      • 6.7. 查询将用户id,名称,年龄拼接的结果
      • 6.8.聚合函数group by的用法:
      • 6.9. 多条件查询:
      • 6.10. 多表查询:
  • 三、spring data jpa 简单入门笔记

一、 Querydsl面试常识问题

1.Querydsl是什么?

  维护HQL查询官方封装类 Spring Data Querydsl 支持JPA,JDO,JDBC,Lucene,Hibernate Search,MongoDB,Collections和RDFBean作为它的后端。

二、简单项目使用

1.pom依赖

<dependency><groupId>com.querydsl</groupId><artifactId>querydsl-jpa</artifactId>
</dependency>
<dependency><groupId>com.querydsl</groupId><artifactId>querydsl-apt</artifactId><scope>provided</scope>
</dependency>

2.新增插件,自动生成Q版实体类:

<!-- query dsl 构建Q版实体类的插件-->
<plugin><groupId>com.mysema.maven</groupId><artifactId>apt-maven-plugin</artifactId><version>1.1.3</version><executions><execution><goals><goal>process</goal></goals><configuration><outputDirectory>target/generated-sources/java</outputDirectory><processor>com.querydsl.apt.jpa.JPAAnnotationProcessor</processor></configuration></execution></executions>
</plugin>

3.JPAQueryFactory配置:

  作用:使用QueryDSL的功能时,会依赖使用到JPAQueryFactory,而JPAQueryFactory在这里依赖使用EntityManager,所以在主类中做如下配置,使得Spring自动帮我们注入EntityManager与自动管理JPAQueryFactory

package com.example.querydsljpademo.config;import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.persistence.EntityManager;/**
* 使用QueryDSL的功能时,会依赖使用到JPAQueryFactory,而JPAQueryFactory在这里依赖使用EntityManager,
* 所以在主类中做如下配置,使得Spring自动帮我们注入EntityManager与自动管理JPAQueryFactory
* @author NJ
* @create 2022/12/5 15:12
*/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {@Beanpublic JPAQueryFactory jpaQuery(EntityManager entityManager) {return new JPAQueryFactory(entityManager);}
}

4.新建po实体

package com.example.querydsljpademo.entity;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import org.springframework.format.annotation.DateTimeFormat;import javax.persistence.*;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;@Data
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "demo_entity")
@Entity
@Accessors(chain = true)
public class DemoEntity implements Serializable {@Id@GeneratedValueprivate Integer id;private Integer age;private Integer userId;private String name;private Integer height;@DateTimeFormat(pattern = "yyyy-MM-dd")private Date createTime;}

5.使用 compile编译建立Q版对象


代码地址:https://gitee.com/njgitee/querydsl-jpa-demo.git
Querydsl-JPA学习:https://juejin.cn/post/6844903920956014606

6.简单操作-用法:

6.1. 注入 JPAQueryFactory

@Autowired
private JPAQueryFactory jpaQueryFactory;

6.2. 条件查询

@Autowired
private JPAQueryFactory jpaQueryFactory;/**
* 条件查询
*/
@Test
void contation() {QDemoEntity demoEntity = QDemoEntity.demoEntity;//单表获取年龄为10的结果集List<DemoEntity> ageList = jpaQueryFactory.selectFrom(demoEntity).where(demoEntity.age.eq(10)).fetch();System.out.println(ageList);
}

6.3. 模糊查询并排序

/**
* 模糊查询并排序
*/
@Test
void like() {QDemoEntity demoEntity = QDemoEntity.demoEntity;//模糊查询并排序List<DemoEntity> ageList = jpaQueryFactory.selectFrom(demoEntity).where(demoEntity.name.like("%大%")).orderBy(demoEntity.age.desc()).fetch();System.out.println(ageList);
}

6.4. 区间用法(between)

/**
* 区间用法(between)
*/
@SneakyThrows
@Test
void between() {QDemoEntity demoEntity = QDemoEntity.demoEntity;//between 区间的用法:单表获取开始时间是XX-XX 区间的用户String time = "2019-07-22 00:00:00";SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");Date date= df.parse(time);Timestamp nousedate = new Timestamp(date.getTime());String time1 = "2019-07-23 00:00:00";Date date1= df.parse(time1);Timestamp nousedate1 = new Timestamp(date1.getTime());List<DemoEntity> beginTimeList = jpaQueryFactory.selectFrom(demoEntity).where(demoEntity.createTime.between(nousedate, nousedate1)).fetch();System.out.println("单表获取开始时间是XX-XX 区间的用户的结果集:"+beginTimeList);
}

6.5. 分页查询

/**
* 分页查询
*/
@SneakyThrows
@Test
void limit() {Integer pageNo=1;Integer pageSize=10;QDemoEntity demoEntity = QDemoEntity.demoEntity;HashMap<String, Object> result = new HashMap<>();BooleanExpression booleaBuilder = demoEntity.name.like("%大%");long count = jpaQueryFactory.select(demoEntity.count()).from(demoEntity).where(booleaBuilder).fetchOne();List<DemoEntity> list = jpaQueryFactory.select(demoEntity).from(demoEntity).where(booleaBuilder).orderBy(demoEntity.age.desc()).offset((pageNo-1)*pageSize).limit(pageSize).fetch();result.put("content",list);result.put("total",count);result.put("pageNo",pageNo);result.put("pageSize",pageSize);System.out.println("单表获取分页的结果集:"+result);
}

6.6. in查询

/**
* in查询
*/
@SneakyThrows
@Test
void in() {QDemoEntity demoEntity = QDemoEntity.demoEntity;//in 的用法:单表获取年龄是10,20的用户List<Integer> ageLists = new ArrayList<>();ageLists.add(10);ageLists.add(20);List<DemoEntity> ages = jpaQueryFactory.selectFrom(demoEntity).where(demoEntity.age.in(ageLists)).fetch();System.out.println("单表获取年龄是10,20的用户的结果集:"+ages);
}

6.7. 查询将用户id,名称,年龄拼接的结果

/**
* 查询将用户id,名称,年龄拼接的结果
*/
@SneakyThrows
@Test
void concat() {QDemoEntity demoEntity = QDemoEntity.demoEntity;//聚合函数-concat()的使用:单表查询将用户id,名称,年龄拼接的结果List<String> concatList = jpaQueryFactory.select(demoEntity.id.stringValue().concat(demoEntity.name).concat(demoEntity.age.stringValue())).from(demoEntity).fetch();System.out.println("单表查询将用户id,名称,年龄拼接的结果:"+concatList);
}

6.8.聚合函数group by的用法:

/**
* 聚合函数group by的用法:
*/
@SneakyThrows
@Test
void group() {QDemoEntity demoEntity = QDemoEntity.demoEntity;List<Map<String,Object>> tupleJPAQuery = jpaQueryFactory.select(demoEntity.age, demoEntity.count().as("count")).from(demoEntity).groupBy(demoEntity.age).fetch().stream().map(x->{Map<String,Object> resultMap = new HashMap<>();resultMap.put("age",x.get(0,QDemoEntity.class));resultMap.put("count",x.get(1,QDemoEntity.class));return resultMap;}).collect(Collectors.toList());System.out.println("单表分组的结果集:"+tupleJPAQuery);
}

6.9. 多条件查询:

/**
* 多条件查询:
*/
@SneakyThrows
@Test
void booleanBuilder() {QDemoEntity demoEntity = QDemoEntity.demoEntity;//多条件处理BooleanBuilder booleanBuilder = new BooleanBuilder();booleanBuilder.and(demoEntity.age.eq(10));booleanBuilder.and(demoEntity.name.contains("小"));List<DemoEntity> mostlist = jpaQueryFactory.selectFrom(demoEntity).where(booleanBuilder).fetch();System.out.println("单表查询多条件处理的结果:"+mostlist);
}

6.10. 多表查询:

/**
* 多表查询:
*/
@SneakyThrows
@Test
void leftjoin() {QDemoEntity demoEntity = QDemoEntity.demoEntity;QUserEntity userEntity = QUserEntity.userEntity;List<Tuple> tupleList = jpaQueryFactory.select(demoEntity.age,userEntity.height,userEntity.name).from(demoEntity).leftJoin(userEntity).on(demoEntity.userId.eq(userEntity.id)).orderBy(userEntity.age.desc()).fetch();System.out.println("tupleList的结果集:" + tupleList);List<Map<String, Object>> resultList = tupleList.stream().map(x -> {Map<String, Object> resultMap = new HashMap<>();resultMap.put("nameDept", x.get(0, DemoEntity.class));resultMap.put("nameUser", x.get(0, UserEntity.class));resultMap.put("demo-age", x.get(demoEntity.age));resultMap.put("user-height", x.get(userEntity.height));resultMap.put("user-name", x.get(userEntity.name));return resultMap;}).collect(Collectors.toList());System.out.println("resultList的结果集:" + resultList);//封装一下结果集List<DemoDto> list = jpaQueryFactory.select(Projections.bean(DemoDto.class,demoEntity.age,userEntity.height,userEntity.name)).from(demoEntity).leftJoin(userEntity).on(demoEntity.userId.eq(userEntity.id)).orderBy(userEntity.age.desc()).fetch();System.out.println("list的结果集:" + list);
}

三、spring data jpa 简单入门笔记

》》》》》》《spring data jpa 简单入门笔记》

Spring Data Querydsl-JPA 的简单入门笔记相关推荐

  1. spring data jpa从入门到精通_Spring Data JPA的简单入门

    前言 spring data JPA是spring团队打造的sping生态全家桶的一部分,本身内核使用的是hibernate核心源码,用来作为了解java持久层框架基本构成的样本是再好不过的选择.最近 ...

  2. SpringBoot学习笔记:Spring Data Jpa的使用

    更多请关注公众号 Spring Data Jpa 简介 JPA JPA(Java Persistence API)意即Java持久化API,是Sun官方在JDK5.0后提出的Java持久化规范(JSR ...

  3. hql实例 jpa_SpringBoot学习笔记九:Spring Data Jpa的使用

    Spring Data Jpa 简介 JPA JPA(Java Persistence API)意即Java持久化API,是Sun官方在JDK5.0后提出的Java持久化规范(JSR 338,这些接口 ...

  4. 终于有人把Spring Data JPA 讲明白了!

    01 什么是JPA? JPA的全称是 Java Persistence API , 中文的字面意思就是Java 的持久层 API , JPA 就是定义了一系列标准,让实体类和数据库中的表建立一个对应的 ...

  5. 干货|一文读懂 Spring Data Jpa!

    有很多读者留言希望松哥能好好聊聊 Spring Data Jpa!其实这个话题松哥以前零零散散的介绍过,在我的书里也有介绍过,但是在公众号中还没和大伙聊过,因此本文就和大家来仔细聊聊 Spring D ...

  6. Spring Data JPA - 参考文档-3

    参考文档 4. JPA存储库 本章将指出JPA对知识库的支持.这建立在使用Spring Data Repositories中解释的核心存储库支持上.所以要确保你对这里解释的基本概念有一个很好的理解. ...

  7. 使用PostgreSQL使用Spring Boot和JPA构建基本应用

    "我喜欢编写身份验证和授权代码." 〜从来没有Java开发人员. 厌倦了一次又一次地建立相同的登录屏幕? 尝试使用Okta API进行托管身份验证,授权和多因素身份验证. 每个不平 ...

  8. 使用Arquillian测试Spring Data + Spring Boot应用程序(第1部分)

    Spring Data的使命是为数据访问提供一个熟悉且一致的,基于Spring的编程模型,同时仍保留基础数据存储的特​​殊特征. 它提供了与一些后端技术的集成,例如JPA,Rest,MongoDB,N ...

  9. Spring Data 什么是Spring Data 理解

    介绍 Spring Data的使命是为数据访问提供熟悉且一致的基于Spring的编程模型,同时仍保留底层数据存储的特​​殊特性. 它使数据访问技术,关系数据库和非关系数据库,map-reduce框架和 ...

最新文章

  1. 食品行业特点及SAP解决方案探讨
  2. c# 调用restful json_微服务调用为啥用RPC框架,http不更简单吗?
  3. SpringMVC如何获取请求带来的各种信息 ||如果我们的请求参数是一个POJO(自定义参数类型), SpringMVC会自动的为这个POJO进行赋值
  4. 【数学与算法】曲线上各点的曲率kappa和倾角theta
  5. 李洪强iOS经典面试题36-简单介绍 ARC 以及 ARC 实现的原理
  6. Honey Dance I believe
  7. 编程开发之--设计模式
  8. 基于MATLAB语音信号的处理与滤波
  9. 【必备知识】摄像机标定基础理论
  10. 全网音乐Music Download v2.1.2
  11. Dos命令查看wifi密码
  12. ps后期调色教程,ps怎么后期调色步骤图
  13. 2.Raspberrypi 3:树莓派开发板入门
  14. 【Luogu】P8195 小智的疑惑
  15. MySQL B+树如何实现联合索引
  16. 撰写SCI论文好用的免费工具(下) - 易智编译EaseEditing
  17. C# TreeView基本操作及其节点增,删,改(3级节点)
  18. python和matlab读取SST数据(海洋的温度)(.nc文件)并绘图
  19. qq能正常使用 网页打不开的解决办法
  20. JavaScript数组与对象比较的正确姿势

热门文章

  1. 十次方项目开发系列【8】:对评论点赞功能开发 Redis的配置和使用
  2. C++中inet_pton、inet_ntop函数
  3. 华硕网络同传+计算机名,HP网络同传使用方法
  4. Python周刊502期
  5. ubuntu 单网卡 安装lede作旁路由
  6. 常见小票打印机打印故障及解决方法汇总视频教程
  7. linux 修改mysql默认端口3306
  8. Sanic部署(1)
  9. 华为ensp NAT 相关配置
  10. 使用java制作文字图片