SpringBoot JPA使用Specification多表查询LEFT JOIN
1.Student
package com.frank.jpaSpecification.entity;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;import javax.persistence.*;/*** @author 小石潭记* @date 2020/12/12 18:32* @Description: ${todo}*/
@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "t_student")
public class Student {@Idprivate Long id;private String name;private String mobile;private Integer age;@ManyToOneprivate Company company;
}
2.Company
package com.frank.jpaSpecification.entity;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;/*** @author 小石潭记* @date 2020/12/12 18:36* @Description: ${todo}*/
@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "t_company")
public class Company {@Id@GeneratedValueprivate Long id;private String name;private String code;private String address;
}
3.StudentRepository
package com.frank.jpaSpecification.repository;import com.frank.jpaSpecification.entity.Student;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Component;/*** @author 小石潭记* @date 2020/12/12 14:21* @Description: ${todo}*/
@Component
public interface StudentRepository extends PagingAndSortingRepository<Student, Integer>, JpaSpecificationExecutor<Student> {
}
4.StudentService
package com.frank.jpaSpecification.service;import com.frank.jpaSpecification.entity.PageStudentRequest;
import com.frank.jpaSpecification.entity.Student;
import com.frank.jpaSpecification.repository.StudentRepository;
import com.frank.jpaSpecification.specification.StudentSpecification;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;/*** @author 小石潭记* @date 2020/12/12 14:22* @Description: ${todo}*/
@Service
public class StudentService {@Autowiredprivate StudentRepository studentRepository;@Autowiredprivate StudentSpecification studentSpecification;public Page<Student> getStudentList(PageStudentRequest studentRequest) {PageRequest pageRequest = PageRequest.of(studentRequest.getPageNumber(), studentRequest.getPageSize());return studentRepository.findAll(studentSpecification.getStudentSpecification(studentRequest), pageRequest);}}
5.StudentSpecification
package com.frank.jpaSpecification.specification;import com.frank.jpaSpecification.entity.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;/*** @author 小石潭记* @date 2020/12/12 14:27* @Description: ${todo}*/
@Component
public class StudentSpecification {/*** root 就是mobile实例 root.get("name") name是属性名 不是数据库字段名* @param paramRequest* @return* */public Specification<Student> getStudentSpecification(PageStudentRequest paramRequest) {return (root, criteriaQuery, criteriaBuilder) -> {// http://localhost:8080/student?companyName=北京&pageNumber=0&pageSize=5&name=明/*// 普通的orPredicate namePre = criteriaBuilder.like(root.get("name"), "%" + paramRequest.getName() + "%");Predicate companyPre = criteriaBuilder.like(root.get("company").get("name"), "%" + paramRequest.getCompanyName() + "%");return criteriaBuilder.or(namePre, companyPre);*/// 使用左连接查询Join<Student, Company> companyJoin = root.join("company", JoinType.LEFT);Predicate namePre = criteriaBuilder.like(root.get("name"), "%" + paramRequest.getName() + "%");Predicate companyPre = criteriaBuilder.like(companyJoin.get("name"), "%" + paramRequest.getCompanyName() + "%");return criteriaBuilder.or(namePre, companyPre);};}}
6.PageStudentRequest 请求体
package com.frank.jpaSpecification.entity;import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;import java.time.LocalDate;
import java.util.List;/*** @author 小石潭记* @date 2020/12/12 14:26* @Description: ${todo}*/
@Data
public class PageStudentRequest {private Integer pageSize = 10;private Integer pageNumber = 1;private String name;private String companyName;
}
7.StudentController
package com.frank.jpaSpecification.controller;import com.frank.jpaSpecification.entity.PageStudentRequest;
import com.frank.jpaSpecification.entity.Student;
import com.frank.jpaSpecification.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;/*** @author 小石潭记* @date 2020/12/12 19:02* @Description: ${todo}*/
@RestController
@RequestMapping("/student")
public class StudentController {@Autowiredprivate StudentService studentService;@GetMappingpublic Page<Student> index(PageStudentRequest pageStudentRequest) {return studentService.getStudentList(pageStudentRequest);}}
8.测试
http://localhost:8080/student?companyName=北京&pageNumber=0&pageSize=5&name=明
student和company的sql
-- --------------------------------------------------------
-- 主机: 127.0.0.1
-- 服务器版本: 5.6.40 - MySQL Community Server (GPL)
-- 服务器操作系统: Win64
-- HeidiSQL 版本: 8.2.0.4675
-- --------------------------------------------------------/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET NAMES utf8 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;-- 导出 test 的数据库结构
CREATE DATABASE IF NOT EXISTS `test` /*!40100 DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_bin */;
USE `test`;-- 导出 表 test.t_company 结构
CREATE TABLE IF NOT EXISTS `t_company` (`id` bigint(20) NOT NULL,`address` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL,`code` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL,`name` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;-- 正在导出表 test.t_company 的数据:~1 rows (大约)
DELETE FROM `t_company`;
/*!40000 ALTER TABLE `t_company` DISABLE KEYS */;
INSERT INTO `t_company` (`id`, `address`, `code`, `name`) VALUES(1, '重庆', '023', '重庆沙坪坝科技公司'),(2, '成都', '028', '成都高新区有限公司'),(3, '北京', '021', '北京朝阳区科技公司');
/*!40000 ALTER TABLE `t_company` ENABLE KEYS */;-- 导出 表 test.t_student 结构
CREATE TABLE IF NOT EXISTS `t_student` (`id` bigint(20) NOT NULL AUTO_INCREMENT,`age` int(11) DEFAULT NULL,`mobile` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL,`name` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL,`company_id` bigint(20) DEFAULT NULL,PRIMARY KEY (`id`),KEY `FK3k0qejwy2hdw7n0qauh6vfk7l` (`company_id`),CONSTRAINT `FK3k0qejwy2hdw7n0qauh6vfk7l` FOREIGN KEY (`company_id`) REFERENCES `t_company` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;-- 正在导出表 test.t_student 的数据:~0 rows (大约)
DELETE FROM `t_student`;
/*!40000 ALTER TABLE `t_student` DISABLE KEYS */;
INSERT INTO `t_student` (`id`, `age`, `mobile`, `name`, `company_id`) VALUES(1, 18, '18000000000', '小花', 1),(2, 21, '18000000000', '小花', 2),(3, 23, '18000000010', '小明', 2),(4, 17, '18000000000', '小花', 3),(5, 22, '18000000000', '小猪', 1),(6, 25, '18000000055', '小花', 1),(7, 26, '18000000000', '小六', 3),(8, 20, '18000000785', '小花', 1),(9, 19, '18000000000', '小菊', 2),(10, 28, '18000004521', '小花', 1),(11, 19, '18000000000', '小军', 1);
/*!40000 ALTER TABLE `t_student` ENABLE KEYS */;
/*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */;
/*!40014 SET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS IS NULL, 1, @OLD_FOREIGN_KEY_CHECKS) */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
自此左连接查询完毕,左连接查询: 就是已左边的表为基准,先将左表查出的数据显示出来,再显示关联的右表中查询出的数据,没有关联数据则字段值以null展示。
SpringBoot JPA使用Specification多表查询LEFT JOIN相关推荐
- Springboot使用Specification连表查询LEFT
大致目录机构 package com.frank.leftQuery.entity;import lombok.AllArgsConstructor; import lombok.Data; impo ...
- mysql 多表查询 join on_MySQL多表查询Left Join,Right Join学习笔记
http://my.oschina.net/adamboy/blog MySQL多表连接查询Left Join,Right Join php开源嘛 在讲MySQL的Join语法前还是先回顾一下联结的语 ...
- inner join去除重复_SQL多表查询:join表联结
在之前的学习和练习中,所有的操作都是在一张表中进行操作,实际工作中,我们期望得到的数据往往分散在不同的表中,今天我将带大家一起学会从多张表中获取数据. 一.表的加法 表的加法在SQL语句中用union ...
- SpringBoot JPA(JpaRepository)动态查询 分页展示
大家知道Hibernate可以很轻松的根据提供条件进行动态筛选查询,那个JPA怎么实现呢,其中最为简单的就是使用Specification实现JPA的动态查询,本人也是初步接触JPA,第一次使用JPA ...
- mysql 同一张表查询_mysql 同一张表查询 left join
今天群里有同学发了一个题: 一张表,如图 需要写一个sql ,输出如下结果 对这个表进行一下简单解释,其实就是省市区的关系,放在了同一张表中,level=1表示省, level=2表示市,level= ...
- 数据库mysql自然连接_MySQL数据库之多表查询natural join自然连接
自然连接 概念 自动判断条件连接,判断的条件是依据同名字段 小结 表连接是通过同名字段来连接的 如果没有同名字段就返回笛卡尔积 同名的连接字段只显示一个,并且将该字段放在最前面 自然内连接(natur ...
- 基于SpringDataJpa的mysql动态分页多表查询
基于SpringDataJpa的mysql动态分页多表查询 由于这篇文章预计篇幅会很长,关于Spring Data JPA的知识就简短的分享,更多的请自行度娘,JPA 封装了很多查询的接口,但今天要讲 ...
- 4,表查询语法,表连接,子查询
数据库基础四: 今日内容: 一:单表查询语法 from 找表 where 第一次筛选 group by 分组 having 二次筛选 distinct 去重(数据一模一样时去重复的,在from之前使用 ...
- mysql 连边聚合_MySQL分组,聚合函数,连表查询,子查询
>>>分组: group by + group_concat 分组:类似于将一个班级的学生,按照性别或其他条件,分成若干个组,最终以小组为单位显示,如上图中,以post字段对表进行分 ...
最新文章
- Oracle Goldengate Windows平台Oracle-Oracle单向复制
- (转)java.lang.OutOfMemoryError: Java heap space错误及处理办法(收集整理、转)
- python--socket套接字/TCP
- Qt下Tcp通信的简单使用三
- PHP函数-判断字符是否在于指定的字符串中
- android工程师入职必装软件
- 2021年中国超光谱成像系统(HSI)市场趋势报告、技术动态创新及2027年市场预测
- php公众号失物招领系统,【服务】微信公众平台『失物招领』功能上线
- duet display连接不上怎么办
- 阿里云移动推送学习笔记
- 电子计算机上total,计算器频幕上grand total 什么意思
- 软件测试--因果图分析方法
- ART 虚拟机 — Interpreter 模式
- (转)Apple Push Notification Services in iOS 6 Tutorial: Part 1/2
- 【Qt开发】QThread中的互斥、读写锁、信号量、条件变量
- 【HDU 5765】Bonds(进制运算妙用)
- 电脑经常出现程序未响应
- 树莓派上编写串口助手软件
- 51单片机入门学习 第七天
- 帮转|腾讯云市场新版上线:大不同