通用mapper批量插入

批量插入分两种情况:1、主键自增 2、主键不自增

第一种:主键自增

mybatis自带的批量插入方法insertList();
dao层接口继承 InsertListMapper<自定义类>

public interface OrderDetailMapper extends Mapper<OrderDetail>, InsertListMapper<OrderDetail> {
    void saveOrderDetails(List<OrderDetail> orderDetailList);
}

在service层直接调用OrderDetailMapper.insertList()

第二种:主键不自增

自己写sql 使用mybatis的foreach方法

public interface OrderDetailMapper extends Mapper<OrderDetail>{
    void saveOrderDetails(List<OrderDetail> orderDetailList);
}
   <insert id="saveOrderDetails">
        insert into order_detail (id,order_id,item_id,order_price,order_num) values
        <foreach collection="list" item="item" index="index" separator=",">
            (
            #{item.id},#{item.orderId},#{item.itemId},#{item.orderPrice},#{item.orderNum}
            )
        </foreach>
    </insert>

service层调用OrderDetailMapper.saveOrderDetails()

你可能感兴趣的:(mybatis,spring)