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

mybatisplus的高级用法总结 mybatisplusforeach

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

相关推荐

Mysql和Oracle实现序列自增(oracle创建序列的sql)

Mysql和Oracle实现序列自增/*ORACLE设置自增序列oracle本身不支持如mysql的AUTO_INCREMENT自增方式,我们可以用序列加触发器的形式实现,假如有一个表T_WORKM...

关于Oracle数据库12c 新特性总结(oracle数据库19c与12c)

概述今天主要简单介绍一下Oracle12c的一些新特性,仅供参考。参考:http://docs.oracle.com/database/121/NEWFT/chapter12102.htm#NEWFT...

MySQL CREATE TABLE 简单设计模板交流

推荐用MySQL8.0(2018/4/19发布,开发者说同比5.7快2倍)或同类型以上版本....

mysql学习9:创建数据库(mysql5.5创建数据库)

前言:我也是在学习过程中,不对的地方请谅解showdatabases;#查看数据库表createdatabasename...

MySQL面试题-CREATE TABLE AS 与CREATE TABLE LIKE的区别

执行"CREATETABLE新表ASSELECT*FROM原表;"后,新表与原表的字段一致,但主键、索引不会复制到新表,会把原表的表记录复制到新表。...

Nike Dunk High Volt 和 Bright Spruce 预计将于 12 月推出

在街上看到的PandaDunk的超载可能让一些球鞋迷们望而却步,但Dunk的浪潮仍然强劲,看不到尽头。我们看到的很多版本都是为女性和儿童制作的,这种新配色为后者引入了一种令人耳目一新的新选择,而...

美国多功能舰载雷达及美国海军舰载多功能雷达系统技术介绍

多功能雷达AN/SPY-1的特性和技术能力,该雷达已经在美国海军服役了30多年,其修改-AN/SPY-1A、AN/SPY-1B(V)、AN/SPY-1D、AN/SPY-1D(V),以及雷神...

汽车音响怎么玩,安装技术知识(汽车音响怎么玩,安装技术知识视频)

全面分析汽车音响使用或安装技术常识一:主机是大多数人最熟习的音响器材,有关主机的各种性能及规格,也是耳熟能详的事,以下是一些在使用或安装时,比较需要注意的事项:LOUDNESS:几年前的主机,此按...

【推荐】ProAc Response系列扬声器逐个看

有考牌(公认好声音)扬声器之称ProAcTablette小音箱,相信不少音响发烧友都曾经,或者现在依然持有,正当大家逐渐掌握Tablette的摆位设定与器材配搭之后,下一步就会考虑升级至表现更全...

#本站首晒# 漂洋过海来看你 — BLACK&amp;DECKER 百得 BDH2000L无绳吸尘器 开箱

作者:初吻给了烟sco混迹张大妈时日不短了,手没少剁。家里有了汪星人,吸尘器使用频率相当高,偶尔零星打扫用卧式的实在麻烦(汪星人:你这分明是找借口,我掉毛是满屋子都有,铲屎君都是用卧式满屋子吸的,你...

专题|一个品牌一件产品(英国篇)之Quested(罗杰之声)

Quested(罗杰之声)代表产品:Q212FS品牌介绍Quested(罗杰之声)是录音监听领域的传奇品牌,由英国录音师RogerQuested于1985年创立。在成立Quested之前,Roger...

常用半导体中英对照表(建议收藏)(半导体英文术语)

作为一个源自国外的技术,半导体产业涉及许多英文术语。加之从业者很多都有海外经历或习惯于用英文表达相关技术和工艺节点,这就导致许多英文术语翻译成中文后,仍有不少人照应不上或不知如何翻译。为此,我们整理了...

Fyne Audio F502SP 2.5音路低音反射式落地音箱评测

FyneAudio的F500系列,有新成员了!不过,新成员不是新的款式,却是根据原有款式提出特别版。特别版产品在原有型号后标注了SP字样,意思是SpecialProduction。Fyne一共推出...

有哪些免费的内存数据库(In-Memory Database)

以下是一些常见的免费的内存数据库:1.Redis:Redis是一个开源的内存数据库,它支持多种数据结构,如字符串、哈希表、列表、集合和有序集合。Redis提供了快速的读写操作,并且支持持久化数据到磁...

RazorSQL Mac版(SQL数据库查询工具)

RazorSQLMac特别版是一款看似简单实则功能非常出色的SQL数据库查询、编辑、浏览和管理工具。RazorSQLformac特别版可以帮你管理多个数据库,支持主流的30多种数据库,包括Ca...

取消回复欢迎 发表评论: