龙空技术网

mybatisplus的高级用法总结

叫我耀南 228

前言:

现时兄弟们对“log4jxml输出到控制台”大概比较珍视,兄弟们都需要剖析一些“log4jxml输出到控制台”的相关知识。那么小编在网络上网罗了一些有关“log4jxml输出到控制台””的相关资讯,希望你们能喜欢,朋友们一起来学习一下吧!

总结一下偶尔项目中用到的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> {}
使用关联查询
@Autowiredprivate 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;@Datapublic 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;@Servicepublic 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;@Servicepublic 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;@SpringBootTestpublic 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>>() {        });    }}

标签: #log4jxml输出到控制台