MyBatis-Plus联表查询以及分页代码实例
作者:李长渊哦 发布时间:2023-11-26 01:51:32
一、准备工作
mybatis-plus作为mybatis的增强工具,它的出现极大的简化了开发中的数据库操作,但是长久以来,它的联表查询能力一直被大家所诟病。一旦遇到left join或right join的左右连接,你还是得老老实实的打开xml文件,手写上一大段的sql语句。
直到前几天,偶然碰到了这么一款叫做mybatis-plus-join的工具(后面就简称mpj了),使用了一下,不得不说真香!彻底将我从xml地狱中解放了出来,终于可以以类似mybatis-plus中QueryWrapper的方式来进行联表查询了,话不多说,我们下面开始体验。
mapper继承MPJBaseMapper (必选)
service继承MPJBaseService (可选)
serviceImpl继承MPJBaseServiceImpl (可选)
1、数据库结构以及数据
CREATE TABLE `op_product` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`type` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
INSERT INTO `test_yjdsns`.`op_product`(`id`, `type`) VALUES (1, '苹果');
CREATE TABLE `op_product_info` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`product_id` int(11) NOT NULL,
`name` varchar(255) DEFAULT NULL,
`price` decimal(10,2) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
INSERT INTO `test_yjdsns`.`op_product_info`(`id`, `product_id`, `name`, `price`) VALUES (1, 1, '苹果13', 8.00);
INSERT INTO `test_yjdsns`.`op_product_info`(`id`, `product_id`, `name`, `price`) VALUES (2, 1, '苹果15', 9.00);
2、依赖
<dependency>
<groupId>com.github.yulichang</groupId>
<artifactId>mybatis-plus-join</artifactId>
<version>1.2.4</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
3、配置类让mybatis-plus-join在DataScopeSqlInjector中生效
/**
* @author licy
* @description
* @date 2022/10/20
*/
@Configuration
public class MybatisPlusConfig {
/**
* 新增分页 * ,并设置数据库类型为mysql
*
* @return
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
//分页插件
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
/**
* sql注入
*/
@Bean
@Primary
public MySqlInjector myLogicSqlInjector() {
return new MySqlInjector();
}
}
修改DataScopeSqlInjector中的继承类为:MPJSqlInjector
public class MySqlInjector extends MPJSqlInjector {
@Override
public List<AbstractMethod> getMethodList(Class<?> mapperClass) {
//将原来的保持
List<AbstractMethod> methodList = super.getMethodList(mapperClass);
//多表查询sql注入 从连表插件里移植过来的
methodList.add(new SelectJoinOne());
methodList.add(new SelectJoinList());
methodList.add(new SelectJoinPage());
methodList.add(new SelectJoinMap());
methodList.add(new SelectJoinMaps());
methodList.add(new SelectJoinMapsPage());
return methodList;
}
}
4、启动类排除MPJSqlInjector.class
@SpringBootApplication(exclude = {MPJSqlInjector.class})
载入自定义配置类
@Configuration
@MapperScan可以选择tk下的路径
import tk.mybatis.spring.annotation.MapperScan;
二、代码
1、实体类
/**
* @author licy
* @description
* @date 2022/10/25
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName("op_product")
public class OpProduct implements Serializable {
private static final long serialVersionUID = -3918932563888251866L;
@TableId(value = "ID", type = IdType.AUTO)
private Long id;
@TableField("TYPE")
private String type;
}
/**
* @author licy
* @description
* @date 2022/10/25
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName("op_product_info")
public class OpProductInfo implements Serializable {
private static final long serialVersionUID = 4186082342917210485L;
@TableId(value = "ID", type = IdType.AUTO)
private Long id;
@TableField("PRODUCT_ID")
private Long productId;
@TableField("NAME")
private String name;
@TableField("PRICE")
private Double price;
}
/**
* @author licy
* @description
* @date 2022/10/25
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ProductDTO implements Serializable {
private static final long serialVersionUID = -2281333877153304329L;
private Long id;
private String type;
private String name;
private Double price;
}
2、Mapper
/**
* @author licy
* @description
* @date 2022/10/26
*/
public interface OpProductInfoMapper extends MPJBaseMapper<OpProductInfo> {
}
/**
* @author licy
* @description
* @date 2022/10/25
*/
public interface OpProductMapper extends MPJBaseMapper<OpProduct> {
}
3、Service
Mapper接口改造完成后,我们把它注入到Service中,虽然说我们要完成3张表的联表查询,但是以OpProduct作为主表的话,那么只注入这一个对应的OpProductMapper就可以,非常简单。
public interface OpProductService extends MPJBaseService<OpProduct> {
List<ProductDTO> queryAllProduct();
}
@Service
@Slf4j
@AllArgsConstructor
public class OpProductServiceImpl extends MPJBaseServiceImpl<OpProductMapper, OpProduct> implements OpProductService {
@Resource
private OpProductMapper opProductMapper;
@Override
public List<ProductDTO> queryAllProduct() {
MPJLambdaWrapper mpjLambdaWrapper = new MPJLambdaWrapper<ProductDTO>()
.selectAll(OpProduct.class)//查询表1的全部字段
.selectAll(OpProductInfo.class)//查询表2的全部字段
.leftJoin(OpProductInfo.class, OpProductInfo::getProductId, OpProduct::getId);//左查询表2条件为表二的productId=表一的id
List<ProductDTO> list = opProductMapper.selectJoinList(ProductDTO.class, mpjLambdaWrapper);
return list;
}
}
4、测试
@SpringBootTest
@Slf4j
public class MybatisJoinTests {
@Autowired
private OpProductService opProductService;
@Test
void test1() {
List<ProductDTO> productDTOS = opProductService.queryAllProduct();
log.info(productDTOS.toString());
}
}
5、结果
三、分页查询
1、MPJLambdaWrapper几个方法
接下来的MPJLambdaWrapper就是构建查询条件的核心了,看一下我们在上面用到的几个方法:
selectAll():查询指定实体类的全部字段
select():查询指定的字段,支持可变长参数同时查询多个字段,但是在同一个select中只能查询相同表的字段,所以如果查询多张表的字段需要分开写
selectAs():字段别名查询,用于数据库字段与接收结果的dto中属性名称不一致时转换
leftJoin():左连接,其中第一个参数是参与联表的表对应的实体类,第二个参数是这张表联表的ON字段,第三个参数是参与联表的ON的另一个实体类属性
除此之外,还可以正常调用mybatis-plus中的各种原生方法,文档中还提到,默认主表别名是t,其他的表别名以先后调用的顺序使用t1、t2、t3以此类推。
和mybatis-plus非常类似,除了LamdaWrapper外还提供了普通QueryWrapper的写法,举例代码:
public void getOrderSimple() {
List<xxxxxDto> list = xxxxxMapper.selectJoinList(xxxxx.class,
new MPJQueryWrapper<xxxxx>()
.selectAll(xxxxx.class)
.select("t2.unit_price","t2.name as product_name")
.select("t1.name as user_name")
.leftJoin("t_user t1 on t1.id = t.user_id")
.leftJoin("t_product t2 on t2.id = t.product_id")
.eq("t.status", "3")
);
log.info(list.toString());
}
或者
MPJLambdaWrapper mpjLambdaWrapper = new MPJLambdaWrapper<ProductDTO>()
.selectAll(OpProduct.class)//查询表1的全部字段
.selectAs(OpProductInfo::getId,"ProductInfoId")//起别名
.selectAs(OpProductInfo::getName,ProductDTO::getName)//起别名
.selectAs(OpProductInfo::getPrice,ProductDTO::getPrice)//起别名
.leftJoin(OpProductInfo.class, OpProductInfo::getProductId, OpProduct::getId);//左查询表2条件为表二的productId=表一的id
List<ProductDTO> list = opProductMapper.selectJoinList(ProductDTO.class, mpjLambdaWrapper);
return list;
2、分页代码举例
public IPage<ProductDTO> queryPageProduct(Integer pageNo, Integer pageCount) {
MPJLambdaWrapper mpjLambdaWrapper = new MPJLambdaWrapper<ProductDTO>()
.selectAll(OpProduct.class)//查询表1的全部字段
.selectAll(OpProductInfo.class)//查询表2的全部字段
.leftJoin(OpProductInfo.class, OpProductInfo::getProductId, OpProduct::getId);//左查询表2条件为表二的productId=表一的id
IPage<ProductDTO> page = opProductMapper.selectJoinPage(new Page<ProductDTO>(pageNo, pageCount), ProductDTO.class, mpjLambdaWrapper);
return page;
}
来源:https://blog.csdn.net/weixin_46146718/article/details/125279384


猜你喜欢
- 本文实例讲述了android中ListView数据刷新时的同步方法。分享给大家供大家参考。具体实现方法如下:public class Mai
- 前言idea作为一个java开发的便利IDE工具,个人是比较喜欢的,今天来探索个小功能: 导出单个类文件为jar包!JAR文件的全称是Jav
- About Spring开源免费框架,轻量级,非入侵式框架。Spring就是一个轻量级的控制反转(IOC)和面向切片编程(AOP)的框架Ma
- 以下内容给大家介绍Android数据存储提供了五种方式:1、SharedPreferences2、文件存储3、SQLite数据库4、Cont
- 直接插入排序<code class="language-java hljs ">import java.ut
- 编写规范目的:能够在编码过程中实现规范化,为以后的程序开发中养成良好的行为习惯。1、 项目名全部小写2、 包名全部小写3、 类名首字母大写,
- 本文实例讲述了C#实现的SQL备份与还原功能。分享给大家供大家参考,具体如下://记得加 folderBrowserDialog1 open
- 实现 bean 初始化、摧毁方法的配置与处理spring支持我们自定义 bean 的初始化方法和摧毁方法。配置方式可以通过 xml 的 in
- 本文实例讲述了Android实现ListView控件的多选和全选功能。分享给大家供大家参考,具体如下:主程序代码MainActivity.J
- 1)页面跳转 直接返回字符串:此种方式会将返回的字符串与视图解析器的前后缀拼接后跳转。 返回带有前缀的字符串:转发:
- 前言现在的项目一般是拆分成一个个独立的模块,当在其他项目中想要使用独立出来的这些模块,只需要在其pom.xml使用<dependenc
- 本文实例为大家分享了Java实现图书借阅系统的具体代码,供大家参考,具体内容如下为图书阅览室开发一个图书借阅系统,最多可存50本图书,实现图
- 前言最近测试反馈一个问题,某个查询全量信息的接口,有时候返回全量数据,符合预期,但是偶尔又只返回1条数据,简直就是“见鬼
- 本文实例为大家分享了Android绝对布局AbsoluteLayout的具体代码,供大家参考,具体内容如下1>AbsoluteLayo
- Java的在还没有发现新写法之前时,我一直是这么初始化List跟Map://初始化List List&l
- 1. 基础知识集合Java.util包下的常用子类,集合无非就是各种数据结构的应用。集合存在的目的就是为了将数据高效的进行读写,无论哪种具体
- 这里以list为介绍:private static readonly T[] s_emptyArray = new T[0];public
- 本文实例为大家分享了Android实现比赛时间闪动效果的具体代码,供大家参考,具体内容如下效果代码上代码public class Twink
- 目录安装 BenchmarkDotNet什么是基准测试创建基准测试代码运行 benchmarkBenchmarkDotNet 是一个轻量级,
- 接触过Android开发的同学们都知道在Android中访问程序资源基本都是通过资源ID来访问。这样开发起来很简单,并且可以不去考虑各种分辨