如何在MyBatis的mapper.xml文件编写批量新增的语句?

dao 层提供的接口如下:

/**
 * 批量增加用户
 * @param userList
 * @return
 */
public int addUserBatch(List<Test> testList);

这里为了添加记录方便,用了一个简单的 Test 实体类:

package com.qjl.ssm.sysmanage.entity;

public class Test {
    private Integer id;
    private String name;
    private String info;

    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getInfo() {
        return info;
    }
    public void setInfo(String info) {
        this.info = info;
    }
}

批量新增的语句如下:

<!-- 批量增加 -->
<insert id="addUserBatch" parameterType="list">
    INSERT into test (name, info) VALUES
    <foreach collection="list" item="test" separator=",">
        (#{test.name},#{test.info})
    </foreach>
</insert>

前台的 jsp 页面:

<h1>批量新增Test</h1>
<form action="<%=path%>/sysmgr/user/batchAddUser" method="post">
<table>
    <thead>
        <tr>
            <th>姓名</th>
            <th>信息</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><input type="text" name="testList[0].name" /></td>
            <td><input type="text" name="testList[0].info" /></td>
        </tr>
        <tr>
            <td><input type="text" name="testList[1].name" /></td>
            <td><input type="text" name="testList[1].info" /></td>
        </tr>
        <tr>
            <td><input type="text" name="testList[2].name" /></td>
            <td><input type="text" name="testList[2].info" /></td>
        </tr>
    </tbody>
</table>
<input type="submit" value="批量新增测试" />
</form>

springMVC 接收请求的代码如下:

@RequestMapping("/batchAddUser")
public String batchAddUser(TestDTO testDTO, Model model) {

    this.userService.addUserBatch(testDTO.getTestList());
    return "forward:/sysmgr/user/getUserList";
}

TestDTO 代码如下:

package com.qjl.ssm.sysmanage.dto;

import java.util.List;

import com.qjl.ssm.sysmanage.entity.Test;

public class TestDTO {

    private List<Test> testList;

    public List<Test> getTestList() {
        return testList;
    }

    public void setTestList(List<Test> testList) {
        this.testList = testList;
    }
}

猜你喜欢

转载自blog.csdn.net/a909301740/article/details/80549834