myBatis中使用批量插入操作

例:
数据库表名为:student
实体类所在包路径:com.test.entity.Student
实体类:

@Data
public class Student{
//姓名
private String name;
//性别
private String age;
//年龄
private String gender;
}

Controller:

@RestController
@RequestMapping("/test")
public class test{
     @Resource
     private StudentService studentService;
     @PostMapping("insertStudent")
	 public void insertStudent(@RequestBody List<Student> student){
	   studentService.insertStudent(student);
	 }
}

service:

public interface studentService{
  public void insertStudent(List<Student> student);
}

impl:

@Service
public class studentServiceImpl implements  studentService{
   @Resource
   private StudentMapper studentMapper;
	@Override
	public void insertStudent(List<Student> student){
	  studentMapper.insertStudent(student);
	}
}

mapper:

@Mapper
public interface StudentMapper{
  public void insertStudent(List<Student> student);
}

mapper.xml

<insert id="insertStudent" useGeneratedKeys="true" keyProperty="id" parameterType="com.test.entity.Student">
        insert into student(
        id,name,age,gender)
        values
        <foreach collection="list" item="student" index="index" separator=",">
            (#{student.id},#{student.name},#{student.age},#{student.gender})
        </foreach>
</insert>

知识补充:
foreach元素的属性主要有 item,index,collection,open,separator,close。

  1. item表示集合中每一个元素进行迭代时的别名,

  2. index指 定一个名字,用于表示在迭代过程中,每次迭代到的位置,

  3. open表示该语句以什么开始,

  4. separator表示在每次进行迭代之间以什么符号作为分隔 符,

  5. close表示以什么结束。
    在使用foreach的时候最关键的也是最容易出错的就是collection属性:

  6. 如果传入的是单参数且参数类型是一个List的时候,collection属性值为list

  7. 如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array

  8. 如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了,当然单参数也可

上面所示的例子是以list为参数!!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值