当前位置: 首页 > news >正文

Mybatis实现批量添加

1.设计一张商品表
CREATE TABLE IF NOT EXISTS goods (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255) NOT NULL
);
2.编写实体类映射数据库表格
@Data
public class Goods {
    private Long id;
    private String name;

    // Getters and Setters
}
3.编写持久层接口以及其对应sql
@Mapper
public interface GoodsMapper {
    @Insert("<script>" +
            "INSERT INTO goods (name) VALUES " +
            "<foreach collection='goodsList' item='item' separator=','>" +
            "(#{item.name})" +
            "</foreach>" +
            "</script>")
    void batchInsert(@Param("goodsList") List<Goods> goodsList);
}
4.编写服务层类
@Service
public class GoodsService {
    @Autowired
    private GoodsMapper goodsMapper;
    public void batchInsertGoods(List<Goods> goodsList) {
        goodsMapper.batchInsert(goodsList);
    }
}
5.编写控制层类
@RestController
@RequestMapping("/api/goods")
public class GoodsController {
    @Autowired
    private GoodsService goodsService;
    @PostMapping("/batch")
    public String batchInsertGoods(@RequestBody List<Goods> goodsList) {
        try {
            goodsService.batchInsertGoods(goodsList);
            return "Batch insert successful";
        } catch (Exception e) {
            return "Batch insert failed: " + e.getMessage();
        }
    }
}
6.编写前端页面进行批量插入测试
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>批量插入商品</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f9;
            margin: 0;
            padding: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
        }

        .container {
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 15px rgba(0, 0, 0, 0.1);
            width: 300px;
        }

        h1 {
            text-align: center;
            color: #333;
        }

        input[type="text"] {
            width: calc(100% - 22px);
            padding: 10px;
            margin-bottom: 10px;
            border: 1px solid #ccc;
            border-radius: 4px;
        }

        button {
            width: calc(50% - 6px);
            padding: 10px;
            margin: 2px;
            border: none;
            border-radius: 4px;
            background-color: #007BFF;
            color: white;
            cursor: pointer;
        }

        button:hover {
            background-color: #0056b3;
        }

        ul {
            list-style-type: none;
            padding: 0;
        }

        li {
            background-color: #f9f9f9;
            padding: 10px;
            margin-bottom: 5px;
            border-radius: 4px;
            border: 1px solid #ddd;
        }
    </style>
</head>
<body>
<div class="container">
    <h1>批量插入商品</h1>
    <form id="goodsForm">
        <input type="text" id="goodName" placeholder="请输入商品名称"/>
        <div style="display: flex; justify-content: space-between;">
            <button type="button" onclick="addGood()">添加商品</button>
            <button type="button" onclick="submitGoods()">提交商品</button>
        </div>
    </form>
    <ul id="goodsList"></ul>
</div>

<script>
    let goods = [];

    function addGood() {
        const goodName = document.getElementById('goodName').value.trim();
        if (goodName !== '') {
            goods.push({name: goodName});
            renderGoods();
            document.getElementById('goodName').value = '';
        }
    }

    function renderGoods() {
        const goodsListElement = document.getElementById('goodsList');
        goodsListElement.innerHTML = '';
        goods.forEach((good, index) => {
            const li = document.createElement('li');
            li.textContent = `${index + 1}: ${good.name}`;
            goodsListElement.appendChild(li);
        });
    }

    async function submitGoods() {
        const response = await fetch('/api/goods/batch', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(goods)
        });

        const result = await response.text();
        alert(result);
        if (response.ok) {
            goods = [];
            renderGoods();
        }
    }
</script>
</body>
</html>

在这里插入图片描述

在这里插入图片描述

相关文章:

  • rust学习笔记11-集合349. 两个数组的交集
  • FreeRTOS系列---程序正常,但任务无法创建
  • Qt之QGraphicsView图像操作
  • C语言--快速排序和归并排序
  • 【回溯】216. 组合总和 III
  • 大模型Agent:人工智能的崭新形态与未来愿景
  • DICOM服务中的C-STORE、 C-FIND、C-MOVE、C-GET、Worklist
  • 一文讲清楚自我学习和深度学习
  • 通过微步API接口对单个IP进行查询
  • postman请求后端接受List集合对象
  • IDEA中Git版本回退终极指南:Reset与Revert双方案详解
  • GIt分支合并
  • PHP 包含(Include)机制详解
  • 向量数据库Chroma的介绍
  • MySQL-高级查询
  • 36-Openwrt wifi命令工具iwconfig、iwinfo、iwpriv、iwlist
  • LeetCode hot 100—环形链表 II
  • Qt中txt文件输出为PDF格式
  • 嵌入式学习-EXTI外部中断
  • Java UDP 通信:实现简单的 Echo 服务器与客户端
  • 做网站建设有哪些公司/搜索引擎营销的概念
  • 铜陵网站制作公司/怎么申请建立网站
  • 上海推广网站公司/网站怎样做推广
  • 网站数据库修改密码要怎么做/广告推广营销网站
  • 用户体验较好的网站/深圳网站优化哪家好
  • 长尾关键词挖掘爱站网/百度推广售后电话