0


No Spring环境Mybatis-Plus批量插入并返回主键的两种方式


批量插入,可以把Mybatis-Plus看作是Mybatis加强版;故Mybatis中的相关操作都可以在Mybatis-Plus中使用;在mysql数据库中支持批量插入,所以只要配置useGeneratedKeys和keyProperty就可以批量插入并返回主键了。

下面是批量插入的Dao层接口


一注解方式:

 直接撸代码:
package org.jd.data.netty.big.window.chat.frame.ui.room.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Param;
import org.jd.data.netty.big.window.chat.entity.SysRandomColor;

import java.util.List;


/**
 * <p>@Description:Mapper随机颜色服务接口</p>
 * <p>@Copyright: Copyright (c)2,023</p>
 * <p>@Company: 北京惠农科技有限公司</p>
 * <P>@Created Date :2023年03月19日</P>
 * <P>@version 1.0
 * <p>@author yh19166</p>
 */
@Mapper
public interface SysRandomColorMapper extends BaseMapper<SysRandomColor> {
    /**
     * 批量插入
     *
     * @param sysRandomColorList 集合参数
     * @return {@link Integer} 返回插入的总条数
     */
    @Insert("<script>" +
            "     insert into sys_random_color (color_zh_name,color_cn_name,color_hexadecimal,color_rgb_value,create_time,update_time) values " +
            " <foreach" +
            "     collection='aList' item='c' separator=','>(#{c.colorZhName},#{c.colorCnName},#{c.colorHexadecimal},#{c.colorRgbValue},#{c.createTime},#{c.updateTime})" +
            " </foreach>" +
            "</script>")
    @Options(useGeneratedKeys = true, keyProperty = "colorId")
    int batchSave(@Param("aList") List<SysRandomColor> sysRandomColorList);

}

第二种: XML方式

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
**<mapper namespace="org.jd.data.netty.big.window.chat.frame.ui.room.mapper.SysRandomColorMapper">

    <insert id="batchSave" useGeneratedKeys="true" keyProperty="colorId">
        insert into sys_random_color (color_zh_name,color_cn_name,color_hexadecimal,color_rgb_value,create_time,update_time)
        values
        <foreach collection="aList" item="c" separator=",">
            (#{c.colorZhName},#{c.colorCnName},#{c.colorHexadecimal},#{c.colorRgbValue},#{c.createTime},#{c.updateTime})
        </foreach>
    </insert>
</mapper>**

测试实例:


package org.jd.data.netty.big.window.chat.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.*;

import java.io.Serializable;
import java.util.Date;

/**
 * <p>@Description: 顾客入住信息领域模型</p>
 * <p>@Copyright: Copyright (c)2,023</p>
 * <p>@Company: 北京惠农科技有限公司</p>
 * <P>@Created Date :2023年03月19日</P>
 * <P>@version 1.0
 * <p>@author yh19166</p>
 */
@TableName("sys_random_color")
@Data
@NoArgsConstructor
public class SysRandomColor implements Serializable {
    /**
     * =========================================================================================
     * 注解名称    功能
     * @Setter 自动添加类中所有属性相关的 set 方法
     * @Getter 自动添加类中所有属性相关的 get 方法
     * @Builder 使得该类可以通过 builder (建造者模式)构建对象
     * @RequiredArgsConstructor 生成一个该类的构造方法,禁止无参构造
     * @ToString 重写该类的toString()方法
     * @EqualsAndHashCode 重写该类的equals()和hashCode()方法
     * @Data 等价于上面的@Setter、@Getter、@RequiredArgsConstructor、@ToString、@EqualsAndHashCode
     * ===========================================================================================
     */

    @TableField(exist = false)
    // 不需要为该字段生成get方法
    @Getter(AccessLevel.NONE)
    @Setter(AccessLevel.NONE)
    private static final long serialVersionUID = 1L;

    /**
     * 颜色ID
     */
    @TableId(value = "color_id", type = IdType.AUTO)
    private Long colorId;

    /**
     * 中文名称
     */
    @TableField(value = "color_zh_name")
    private String colorZhName;

    /**
     * 英文名称
     */
    @TableField(value = "color_cn_name")
    private String colorCnName;

    /**
     * 16进制
     */
    @TableField(value = "color_hexadecimal")
    private String colorHexadecimal;

    /**
     * 颜色RGB值
     */
    @TableField(value = "color_rgb_value")
    private String colorRgbValue;

    /**
     * 创建时间
     */
    private Date createTime;

    /**
     * 更新时间
     */
    private Date updateTime;


    @Override
    public String toString() {
        return "SysRandomColor{" +
                ", colorId = " + colorId +
                ", colorZhName = " + colorZhName +
                ", colorCnName = " + colorCnName +
                ", colorHexadecimal = " + colorHexadecimal +
                ", colorRgbValue = " + colorRgbValue +
                ", createTime = " + createTime +
                ", updateTime = " + updateTime +
                "}";
    }
}


测试类:


package org.jd.data.frame.big.window.service;


import cn.hutool.core.convert.Convert;
import org.jd.data.netty.big.window.chat.entity.SysRandomColor;
import org.jd.data.netty.big.window.chat.frame.ui.room.provider.SysRandomColorProvider;
import org.jd.data.netty.big.window.chat.util.FileReaderLineUtil;
import org.jd.data.netty.big.window.chat.util.handler.BeanInstanceFactoryHandler;
import org.junit.Before;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class SysRandomColorProviderTest {

    private Optional<SysRandomColorProvider> sysRandomColorProviderInstance;

    @Before
    public void init() {
        sysRandomColorProviderInstance = BeanInstanceFactoryHandler.getBeanInstance(SysRandomColorProvider.class);
    }

    @Test
    public void saveSysRandomColor() {
        if (sysRandomColorProviderInstance.isPresent()) {
            SysRandomColorProvider sysRandomColorProvider = sysRandomColorProviderInstance.get();
            Optional<List<FileReaderLineUtil.RandomColor>> result = FileReaderLineUtil.productColor();
            if (result.isPresent()) {
                List<SysRandomColor> targetList = new ArrayList<>();
                result.get().stream().forEach(e -> {
                    // 相同字段属性间的拷贝
                    SysRandomColor sysRandomColor = Convert.convert(SysRandomColor.class, e);
                    targetList.add(sysRandomColor);
                });
                int n = sysRandomColorProvider.batchSaveRandomColor(targetList);
                System.out.println("返回插入的总条数: " + n);
            }

        }
    }

    @Test
    public void list() {
        if (sysRandomColorProviderInstance.isPresent()) {
            SysRandomColorProvider sysRandomColorProvider = sysRandomColorProviderInstance.get();
            List<SysRandomColor> resultList = sysRandomColorProvider.list(null, null);
            System.out.println("resultList: "+resultList);
        }
    }
}


数据提供者:

package org.jd.data.netty.big.window.chat.frame.ui.room.provider;

import org.jd.data.netty.big.window.chat.entity.SysRandomColor;
import org.jd.data.netty.big.window.chat.frame.ui.room.service.SysRandomColorService;
import org.jd.data.netty.big.window.chat.frame.ui.room.service.impl.SysRandomColorServiceImpl;
import org.jd.data.netty.big.window.chat.util.instance.annotion.AutoInstanceServiceBean;

import java.util.List;

public class SysRandomColorProvider {


    private SysRandomColorService sysRandomColorService;

    @AutoInstanceServiceBean(value = SysRandomColorServiceImpl.class)
    public void setSysRandomColorService(SysRandomColorService sysRandomColorService) {
        this.sysRandomColorService = sysRandomColorService;
    }

    public int saveRandomColor(SysRandomColor sysRandomColor){
        return sysRandomColorService.saveSysRandomColor(sysRandomColor);
    }

    public int batchSaveRandomColor(List<SysRandomColor> randomColorList){
        return sysRandomColorService.batchSaveRandomColor(randomColorList);
    }

    public List<SysRandomColor> list(String colorZhName,String colorCnName){
        return sysRandomColorService.list(colorZhName,colorCnName);
    }
}


服务接口及实现类:



package org.jd.data.netty.big.window.chat.frame.ui.room.service;


import org.jd.data.netty.big.window.chat.entity.SysRandomColor;
import java.util.List;

/**
 * <p>@Description: 随机颜色服务接口</p>
 * <p>@Copyright: Copyright (c)2,023</p>
 * <p>@Company: 北京惠农科技有限公司</p>
 * <P>@Created Date :2023年03月19日</P>
 * <P>@version 1.0
 * <p>@author yh19166</p>
 */
public interface SysRandomColorService{

    int saveSysRandomColor(SysRandomColor sysRandomColor);

    int batchSaveRandomColor(List<SysRandomColor> sysRandomColorList);

    /**
     * 获取所有随机颜色记录
      * @param colorZhName
     * @param colorCnName
     * @return {@link List<SysRandomColor>}
     */
    List<SysRandomColor> list(String colorZhName,String colorCnName);

}


package org.jd.data.netty.big.window.chat.frame.ui.room.service.impl;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.ibatis.session.SqlSession;
import org.jd.data.netty.big.window.chat.entity.SysRandomColor;
import org.jd.data.netty.big.window.chat.frame.ui.contant.SsyConstant;
import org.jd.data.netty.big.window.chat.frame.ui.room.mapper.SysRandomColorMapper;
import org.jd.data.netty.big.window.chat.frame.ui.room.service.SysRandomColorService;
import org.jd.data.netty.big.window.chat.util.ProxyDruidPoolUtil;

import java.util.List;

/**
 * <p>@Description: 房间类型信息服务实现类</p>
 * <p>@Copyright: Copyright (c)2,023</p>
 * <p>@Company: 北京惠农科技有限公司</p>
 * <P>@Created Date :2023年03月19日</P>
 * <P>@version 1.0
 * <p>@author yh19166</p>
 */
public class SysRandomColorServiceImpl implements SysRandomColorService {

    private SysRandomColorMapper sysRandomColorMapper;

    @Override
    public int saveSysRandomColor(SysRandomColor sysRandomColor) {
        SqlSession session = ProxyDruidPoolUtil.getSession();
        int result;
        try {
            sysRandomColorMapper = session.getMapper(SysRandomColorMapper.class);
            result = sysRandomColorMapper.insert(sysRandomColor);
            session.commit();
        } catch (Exception e) {
            e.printStackTrace();
            result = SsyConstant.INSERT_DATABASE_ERROR;
            session.rollback();
        } finally {
            sysRandomColorMapper = null; // 帮助垃圾回收
            session.close();
        }
        return result;
    }

    /**
     * 返回总条数
     *
     * @param sysRandomColorList
     * @return
     */
    @Override
    public int batchSaveRandomColor(List<SysRandomColor> sysRandomColorList) {
        SqlSession session = ProxyDruidPoolUtil.getSession();
        int result;
        try {
            sysRandomColorMapper = session.getMapper(SysRandomColorMapper.class);
            result = sysRandomColorMapper.batchSave(sysRandomColorList);
            session.commit();
        } catch (Exception e) {
            session.rollback();
            result = SsyConstant.INSERT_DATABASE_ERROR;
        } finally {
            sysRandomColorMapper = null; // 帮助垃圾回收
            session.close();
        }
        return result;
    }

    @Override
    public List<SysRandomColor> list(String colorZhName, String colorCnName) {
        SqlSession session = ProxyDruidPoolUtil.getSession();
        try {
            QueryWrapper<SysRandomColor> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda()
                    .eq(StrUtil.isNotEmpty(colorCnName), SysRandomColor::getColorCnName, colorCnName)
                    .eq(StrUtil.isNotEmpty(colorZhName), SysRandomColor::getColorZhName, colorZhName)
                    .orderByAsc(SysRandomColor::getCreateTime);
            sysRandomColorMapper = session.getMapper(SysRandomColorMapper.class);
            return sysRandomColorMapper.selectList(queryWrapper);
        } catch (Exception e) {
            return null;
        } finally {
            sysRandomColorMapper = null;
            session.close();
        }
    }

}
标签: spring mybatis java

本文转载自: https://blog.csdn.net/u014635374/article/details/131968317
版权归原作者 蜗牛杨哥 所有, 如有侵权,请联系我们删除。

“No Spring环境Mybatis-Plus批量插入并返回主键的两种方式”的评论:

还没有评论