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

mybatisplus的高级用法总结 mybatisplusforeach

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

相关推荐

Python操作Word文档神器:python-docx库从入门到精通

Python操作Word文档神器:python-docx库从入门到精通动动小手,点击关注...

Python 函数调用从入门到精通:超详细定义解析与实战指南 附案例

一、函数基础:定义与调用的核心逻辑定义:函数是将重复或相关的代码块封装成可复用的单元,通过函数名和参数实现特定功能。它是Python模块化编程的基础,能提高代码复用性和可读性。定义语法:...

等这么长时间Python背记手册终于来了,入门到精通(视频400集)

本文毫无套路!真诚分享!前言:无论是学习任何一门语言,基础知识一定要扎实,基础功非常的重要,找一个有丰富编程经验的老师或者师兄带着你会少走很多弯路,你的进步速度也会快很多,无论我们学习的目的是什么,...

图解Python编程:从入门到精通系列教程(附全套速查表)

引言本系列教程展开讲解Python编程语言,Python是一门开源免费、通用型的脚本编程语言,它上手简单,功能强大,它也是互联网最热门的编程语言之一。Python生态丰富,库(模块)极其丰富,这使...

Python入门教程(非常详细)从零基础入门到精通,看完这一篇就够

本书是Python经典实例解析,采用基于实例的方法编写,每个实例都会解决具体的问题和难题。主要内容有:数字、字符串和元组,语句与语法,函数定义,列表、集、字典,用户输入和输出等内置数据结构,类和对象,...

Python函数全解析:从入门到精通,一文搞定!

1.为什么要用函数?函数的作用:封装代码,提高复用性,减少重复,提高可读性。...

Python中的单例模式:从入门到精通

Python中的单例模式:从入门到精通引言单例模式是一种常用的软件设计模式,它保证了一个类只有一个实例,并提供一个全局访问点。这种模式通常用于那些需要频繁创建和销毁的对象,比如日志对象、线程池、缓存等...

【Python王者归来】手把手教你,Python从入门到精通!

用800个程序实例、5万行代码手把手教你,Python从入门到精通!...

Python从零基础入门到精通:一个月就够了

如果想从零基础到入门,能够全职学习(自学),那么一个月足够了。...

Python 从入门到精通:一个月就够了

要知道,一个月是一段很长的时间。如果每天坚持用6-7小时来做一件事,你会有意想不到的收获。作为初学者,第一个月的月目标应该是这样的:熟悉基本概念(变量,条件,列表,循环,函数)练习超过30个编...

Python零基础到精通,这8个入门技巧让你少走弯路,7天速通编程!

Python学习就像玩积木,从最基础的块开始,一步步搭建出复杂的作品。我记得刚开始学Python时也是一头雾水,走了不少弯路。现在回头看,其实掌握几个核心概念,就能快速入门这门编程语言。来聊聊怎么用最...

神仙级python入门教程(非常详细),从0到精通,从看这篇开始!

python入门虽然简单,很多新手依然卡在基础安装阶段,大部分教程对一些基础内容都是一带而过,好多新手朋友,对一些基础知识常常一知半解,需要在网上查询很久。...

Python类从入门到精通,一篇就够!

一、Python类是什么?大家在生活中应该都见过汽车吧,每一辆真实存在、能在路上跑的汽车,都可以看作是一个“对象”。那这些汽车是怎么生产出来的呢?其实,在生产之前,汽车公司都会先设计一个详细的蓝图...

学习Python从入门到精通:30天足够了,这才是python基础的天花板

当年2w买的全套python教程用不着了,现在送给有缘人,不要钱,一个月教你从入门到精通1、本套视频共487集,本套视频共分4季...

30天Python 入门到精通(3天学会python)

以下是一个为期30天的Python入门到精通学习课程,专为零基础新手设计。课程从基础语法开始,逐步深入到面向对象编程、数据处理,最后实现运行简单的大语言模型(如基于HuggingFace...

取消回复欢迎 发表评论: