mybatisplus的高级用法总结 mybatisplusforeach
yuyutoo 2024-10-12 00:02 5 浏览 0 评论
总结一下偶尔项目中用到的mp的高级用法。
valid的判断
数据源优化更新批量操作
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
druid:
driver-class-name: com.mysql.cj.jdbc.Driver
username: admin
password: admin@110
url: jdbc:mysql://joolun-mysql:3306/prod_joolun_upms?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8&allowMultiQueries=true&allowPublicKeyRetrieval=true&rewriteBatchedStatements=true
最后一个参数rewriteBatchedStatements=true
开启实时日志
# 开启mp的日志(输出到控制台)
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
map-underscore-to-camel-case: true
log-prefix: admin
多表联查
依赖POM
<dependency>
<groupId>com.github.yulichang</groupId>
<artifactId>mybatis-plus-join-boot-starter</artifactId>
<version>1.4.13</version>
</dependency>
创建JOIN MAPPER
public interface FairGroupJoinFairGroupStaffMapper extends MPJBaseMapper<FairGroupStaff> {
}
使用关联查询
@Autowired
private FairGroupJoinFairGroupStaffMapper joinFairGroupStaffMapper;
public R mpJoin(Page page, FairGroupStaff groupStaff) {
if (!StringUtils.hasLength(groupStaff.getGroupId())) {
return R.failed("交易团编号不能为空!");
}
MPJLambdaWrapper<FairGroupStaff> wrapper = new MPJLambdaWrapper<FairGroupStaff>()
.select(FairGroupStaff::getId,
FairGroupStaff::getIdName,
FairGroupStaff::getGroupId,
FairGroupStaff::getAccount,
FairGroupStaff::getCreateTime,
FairGroupStaff::getUpdateTime,
FairGroupStaff::getPassword,
FairGroupStaff::getPhone,
FairGroupStaff::getState,
FairGroupStaff::getJob
).select(FairGroup::getGroupName)
.leftJoin(FairGroup.class,
FairGroup::getId, FairGroupStaff::getGroupId).orderByDesc(FairGroupStaff::getCreateTime);
wrapper.eq(FairGroupStaff::getGroupId, groupStaff.getGroupId());
Page<FairGroupStaffVo> userDTOPage = joinFairGroupStaffMapper.selectJoinPage(page, FairGroupStaffVo.class, wrapper);
return R.ok(userDTOPage);
}
动态JSON字段
实体类配置
@TableName(autoResultMap = true)
字段注解
/**
* 必须开启映射注解
*
* @TableName(autoResultMap = true)
*
* 选择对应的 JSON 处理器,并确保存在对应的 JSON 解析依赖包
*/
@TableField(typeHandler = JacksonTypeHandler.class)
// 或者使用 FastjsonTypeHandler
// @TableField(typeHandler = FastjsonTypeHandler.class)
private OtherInfo otherInfo;
例子
添加POM依赖
<dependencies>
<!-- 其他依赖 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>最新版本</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>最新版本</version>
</dependency>
</dependencies>
sql准备
CREATE TABLE `product` (
`id` INT(11) PRIMARY KEY,
`name` VARCHAR(255),
`data` JSON
);
实体类
import lombok.Data;
@Data
public class Product {
private Integer id;
private String name;
private JSONObject data; // 使用 JSONObject 来存储 JSON 数据
}
数据插入
INSERT INTO `product` (`id`, `name`, `data`)
VALUES (1, '手机', '{"brand":"Apple","price":799}');
查询操作
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;
@Service
public class ProductService {
private final ProductMapper productMapper;
public ProductService(ProductMapper productMapper) {
this.productMapper = productMapper;
}
public Product getProductById(Integer id) {
QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("id", id);
return productMapper.selectOne(queryWrapper);
}
}
更新操作
import org.springframework.stereotype.Service;
@Service
public class ProductService {
private final ProductMapper productMapper;
public ProductService(ProductMapper productMapper) {
this.productMapper = productMapper;
}
public void updateProductPrice(Integer productId, BigDecimal newPrice) {
Product product = getProductById(productId);
JSONObject data = product.getData();
data.put("price", newPrice);
productMapper.updateById(product);
}
}
测试类情况
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.math.BigDecimal;
@SpringBootTest
public class ProductServiceTest {
@Autowired
private ProductService productService;
@Test
public void testGetProduct() {
Integer productId = 1;
Product product = productService.getProductById(productId);
System.out.println("查询商品信息结果:");
System.out.println("Product: " + product);
System.out.println("价格:" + product.getData().getBigDecimal("price"));
// 进行更新操作
BigDecimal newPrice = new BigDecimal(899);
productService.updateProductPrice(productId, newPrice);
// 再次查询商品信息
Product updatedProduct = productService.getProductById(productId);
System.out.println("\n更新后的商品信息:");
System.out.println("Product: " + updatedProduct);
System.out.println("价格:" + updatedProduct.getData().getBigDecimal("price"));
}
}
其他
以上情况只适用于直接对象,如果需要转换的是List集合,那么目前的MP自带的handler不能满足,需要自定义,需要重写handler
package com.baomidou.mybatisplus.samples.typehandler;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.extension.handlers.FastjsonTypeHandler;
import com.baomidou.mybatisplus.samples.typehandler.entity.Wallet;
import java.util.List;
/**
* 自定义复杂类型处理器<br/>
* 重写 parse 因为顶层父类是无法获取到准确的待转换复杂返回类型数据
*/
public class WalletListTypeFastJsonHandler extends FastjsonTypeHandler {
public WalletListTypeFastJsonHandler(Class<?> type) {
super(type);
}
@Override
protected Object parse(String json) {
return JSON.parseObject(json, new TypeReference<List<Wallet>>() {
});
}
}
相关推荐
- 史上最全的浏览器兼容性问题和解决方案
-
微信ID:WEB_wysj(点击关注)◎◎◎◎◎◎◎◎◎一┳═┻︻▄(页底留言开放,欢迎来吐槽)●●●...
-
- 平面设计基础知识_平面设计基础知识实验收获与总结
-
CSS构造颜色,背景与图像1.使用span更好的控制文本中局部区域的文本:文本;2.使用display属性提供区块转变:display:inline(是内联的...
-
2025-02-21 16:01 yuyutoo
- 写作排版简单三步就行-工具篇_作文排版模板
-
和我们工作中日常word排版内部交流不同,这篇教程介绍的写作排版主要是用于“微信公众号、头条号”网络展示。写作展现的是我的思考,排版是让写作在网格上更好地展现。在写作上花费时间是有累积复利优势的,在排...
- 写一个2048的游戏_2048小游戏功能实现
-
1.创建HTML文件1.打开一个文本编辑器,例如Notepad++、SublimeText、VisualStudioCode等。2.将以下HTML代码复制并粘贴到文本编辑器中:html...
- 今天你穿“短袖”了吗?青岛最高23℃!接下来几天气温更刺激……
-
最近的天气暖和得让很多小伙伴们喊“热”!!! 昨天的气温到底升得有多高呢?你家有没有榜上有名?...
- CSS不规则卡片,纯CSS制作优惠券样式,CSS实现锯齿样式
-
之前也有写过CSS优惠券样式《CSS3径向渐变实现优惠券波浪造型》,这次再来温习一遍,并且将更为详细的讲解,从布局到具体样式说明,最后定义CSS变量,自定义主题颜色。布局...
- 你的自我界限够强大吗?_你的自我界限够强大吗英文
-
我的结果:A、该设立新的界限...
- 行内元素与块级元素,以及区别_行内元素和块级元素有什么区别?
-
行内元素与块级元素首先,CSS规范规定,每个元素都有display属性,确定该元素的类型,每个元素都有默认的display值,分别为块级(block)、行内(inline)。块级元素:(以下列举比较常...
-
- 让“成都速度”跑得潇潇洒洒,地上地下共享轨交繁华
-
去年的两会期间,习近平总书记在参加人大会议四川代表团审议时,对治蜀兴川提出了明确要求,指明了前行方向,并带来了“祝四川人民的生活越来越安逸”的美好祝福。又是一年...
-
2025-02-21 16:00 yuyutoo
- 今年国家综合性消防救援队伍计划招录消防员15000名
-
记者24日从应急管理部获悉,国家综合性消防救援队伍2023年消防员招录工作已正式启动。今年共计划招录消防员15000名,其中高校应届毕业生5000名、退役士兵5000名、社会青年5000名。本次招录的...
- 一起盘点最新 Chrome v133 的5大主流特性 ?
-
1.CSS的高级attr()方法CSSattr()函数是CSSLevel5中用于检索DOM元素的属性值并将其用于CSS属性值,类似于var()函数替换自定义属性值的方式。...
- 竞走团体世锦赛5月太仓举行 世界冠军杨家玉担任形象大使
-
style="text-align:center;"data-mce-style="text-align:...
- 学物理能做什么?_学物理能做什么 卢昌海
-
作者:曹则贤中国科学院物理研究所原标题:《物理学:ASourceofPowerforMan》在2006年中央电视台《对话》栏目的某期节目中,主持人问过我一个的问题:“学物理的人,如果日后不...
-
- 你不知道的关于这只眯眼兔的6个小秘密
-
在你们忙着给熊本君做表情包的时候,要知道,最先在网络上引起轰动的可是这只脸上只有两条缝的兔子——兔斯基。今年,它更是迎来了自己的10岁生日。①关于德艺双馨“老艺...
-
2025-02-21 16:00 yuyutoo
你 发表评论:
欢迎- 一周热门
- 最近发表
- 标签列表
-
- mybatis plus (70)
- scheduledtask (71)
- css滚动条 (60)
- java学生成绩管理系统 (59)
- 结构体数组 (69)
- databasemetadata (64)
- javastatic (68)
- jsp实用教程 (53)
- fontawesome (57)
- widget开发 (57)
- vb net教程 (62)
- hibernate 教程 (63)
- case语句 (57)
- svn连接 (74)
- directoryindex (69)
- session timeout (58)
- textbox换行 (67)
- extension_dir (64)
- linearlayout (58)
- vba高级教程 (75)
- iframe用法 (58)
- sqlparameter (59)
- trim函数 (59)
- flex布局 (63)
- contextloaderlistener (56)