百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 编程网 > 正文

mybatisplus的高级用法总结 mybatisplusforeach

yuyutoo 2024-10-12 00:02 9 浏览 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>>() {
        });
    }
}

相关推荐

ETCD 故障恢复(etc常见故障)

概述Kubernetes集群外部ETCD节点故障,导致kube-apiserver无法启动。...

在Ubuntu 16.04 LTS服务器上安装FreeRADIUS和Daloradius的方法

FreeRADIUS为AAARadiusLinux下开源解决方案,DaloRadius为图形化web管理工具。...

如何排查服务器被黑客入侵的迹象(黑客 抓取服务器数据)

---排查服务器是否被黑客入侵需要系统性地检查多个关键点,以下是一份详细的排查指南,包含具体命令、工具和应对策略:---###**一、快速初步检查**####1.**检查异常登录记录**...

使用 Fail Ban 日志分析 SSH 攻击行为

通过分析`fail2ban`日志可以识别和应对SSH暴力破解等攻击行为。以下是详细的操作流程和关键分析方法:---###**一、Fail2ban日志位置**Fail2ban的日志路径因系统配置...

《5 个实用技巧,提升你的服务器安全性,避免被黑客盯上!》

服务器的安全性至关重要,特别是在如今网络攻击频繁的情况下。如果你的服务器存在漏洞,黑客可能会利用这些漏洞进行攻击,甚至窃取数据。今天我们就来聊聊5个实用技巧,帮助你提升服务器的安全性,让你的系统更...

聊聊Spring AI Alibaba的YuQueDocumentReader

序本文主要研究一下SpringAIAlibaba的YuQueDocumentReaderYuQueDocumentReader...

Mac Docker环境,利用Canal实现MySQL同步ES

Canal的使用使用docker环境安装mysql、canal、elasticsearch,基于binlog利用canal实现mysql的数据同步到elasticsearch中,并在springboo...

RustDesk:开源远程控制工具的技术架构与全场景部署实战

一、开源远程控制领域的革新者1.1行业痛点与解决方案...

长安汽车一代CS75Plus2020款安装高德地图7.5

不用破解原车机,一代CS75Plus2020款,安装车机版高德地图7.5,有红绿灯读秒!废话不多讲,安装步骤如下:一、在拨号状态输入:在电话拨号界面,输入:*#518200#*(进入安卓设置界面,...

Zookeeper使用详解之常见操作篇(zookeeper ui)

一、Zookeeper的数据结构对于ZooKeeper而言,其存储结构类似于文件系统,也是一个树形目录服务,并通过Key-Value键值对的形式进行数据存储。其中,Key由斜线间隔的路径元素构成。对...

zk源码—4.会话的实现原理一(会话层的基本功能是什么)

大纲1.创建会话...

Zookeeper 可观测性最佳实践(zookeeper能够确保)

Zookeeper介绍ZooKeeper是一个开源的分布式协调服务,用于管理和协调分布式系统中的节点。它提供了一种高效、可靠的方式来解决分布式系统中的常见问题,如数据同步、配置管理、命名服务和集群...

服务器密码错误被锁定怎么解决(服务器密码错几次锁)

#服务器密码错误被锁定解决方案当服务器因多次密码错误导致账户被锁定时,可以按照以下步骤进行排查和解决:##一、确认锁定状态###1.检查账户锁定状态(Linux)```bash#查看账户锁定...

zk基础—4.zk实现分布式功能(分布式zk的使用)

大纲1.zk实现数据发布订阅...

《死神魂魄觉醒》卡死问题终极解决方案:从原理到实战的深度解析

在《死神魂魄觉醒》的斩魄刀交锋中,游戏卡死犹如突现的虚圈屏障,阻断玩家与尸魂界的连接。本文将从技术架构、解决方案、预防策略三个维度,深度剖析卡死问题的成因与应对之策,助力玩家突破次元壁障,畅享灵魂共鸣...

取消回复欢迎 发表评论: