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

mybatisplus的高级用法总结 mybatisplusforeach

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

相关推荐

网络规划建设原来也可以这么简单!

废话少说,直接上干货。天气炎热,请各位看官老爷静心阅读。整体思路下图是关于网络建设的所有相关领域,接下来我为大家逐一讲解。网络分层...

网络规划设计师笔记-第 1 章 计算机网络原理

计算机网络原理1.1计算机网络概论(P1-10)...

别输在远见上,网工这样做职业规划,比啥都强

01职业中的规划,人生中的buff“职业规划“这个词,其实对很多年轻人,包括曾经年轻的我来说,都不屑一提。...

网络规划设计师学习中(个人自学笔记分享1),有一起学习的吗?

网络规划设计师,上午考试内容学习:第一章:计算机网络概述(上部分):如果你也在一起学习,那么我们来一起学习吧!坚持1年,争取明年一次性通过!...

在微服务中使用 ASP.NET Core 实现事件溯源和 CQRS

概述:事件溯源和命令查询责任分离(CQRS)已成为解决微服务设计的复杂性的强大架构模式。基本CQRS表示形式在本文中,我们将探讨ASP.NETCore如何使你能够将事件溯源和CQRS...

一个基于ASP.NET Core完全开源的CMS 解决方案

...

用 Nginx 部署 ASP.NET Core 应用程序

用Nginx部署ASP.NETCore应用程序步骤如下:在Linux中安装.NETCore运行时和Nginx:...

Asp.net Core启动流程讲解(一)(asp.net core 入门)

asp.netcore默认项目包括项目根目录级的Startup.cs、Program.cs、appsettings.json(appsettings.Development.json)launch...

十天学会ASP之第五天(十天学会asp教程)

学习目的:学会数据库的基本操作1(写入记录)数据库的基本操作无非是:查询记录,写入记录,删除记录,修改记录。今天我们先学习写入记录。先建立一个表单:<formname="form1"met...

ASP.NET Core 的 WebApplication 类

ASP.NETCore提供了3个主机类(Host)。这些类用于配置应用、管理生命周期和启动Web服务。...

ASP.NET Core中的键控依赖注入(.net依赖注入原理)

大家好,我是深山踏红叶,今天我们来聊一聊ASP.NETCore中的FromKeyedServices,它是在.Net8中引入的。这一特性允许通过键(如字符串或枚举)来注册和检索依赖注入(D...

Asp.net常用方法及request和response-a

asp.net教程asp.net常用方法:1、Request.UrlReferrer请求的来源,可以根据这个判断从百度搜的哪个关键词、防下载盗链、防图片盗链,可以伪造(比如迅雷)。(使用全局一般处理...

ASP.NET Core EFCore 属性配置与DbContext 详解

...

asp.net常考面试题(aspnet题库)

asp.net常考面试题一,列举ASP.Net页面之间传递值的几种方式?1,使用QueryString,如:......?id=1;response.Redirect()......2,使用Sessi...

在Windows系统搭建.NET Core环境并创建运行ASP.NET网站

微软于6月27日在红帽DevNation峰会上正式发布了.NETCore1.0、ASP.NET1.0和EntityFrameworkCore1.0,其将全部支持Windows、OSX和...

取消回复欢迎 发表评论: