mybatis使用insert into from在mysql中批量插入数据

使用的数据库自增id,不需要返回id。
批量插入,部分字段值是属性传进来的值,部分字段值是其他两个表联查出来的。

java实体类

/**
 * 购物车 实体类
 * @time   2020-02-10 18:53:30
 */
public class Shopcart {
	//id
	private	Long id;
	//用户Id
	private	Long userId;
	//商品spuId
	private	Long spuId;
	//商品标题
	private	String title;
	//商品spu图片
	private	String img;
	//商品skuId
	private	Long skuId;
	//商品sku价格
	private	Integer price;
	//商品sku名称
	private	String skuName;
	//数量(默认1)
	private	Integer buyCount;
	//状态(默认1)
	private	String istatus;
	//创建时间
	private	Date createDate;

	public Shopcart() {}
	public Shopcart(Long userId, Long skuId, Integer buyCount, String istatus) {
		this.userId = userId;
		this.skuId = skuId;
		this.buyCount = buyCount;
		this.istatus = istatus;
	}
	//省略 getter/setter
}

Mapper.java

/**
 * 购物车 DAO
 * @time  2020-02-10 18:53:30
 */
public interface ShopcartMapper {
	// 不需要返回id
    void insertBatch(List<Shopcart> list);
}

Mapper.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="com.fyts.services.goods.core.mapper.ShopcartMapper">

	<insert id="insertBatch" parameterType="list" useGeneratedKeys="false">
		 INSERT INTO shopcart(user_id, spu_id, title, img, sku_id, price, sku_name, buy_count, istatus, create_date)
		<foreach collection="list" item="item" separator="union all">
			SELECT * FROM (SELECT #{item.userId} AS user_id,b.id AS spu_id,b.title,b.img,c.id AS sku_id,c.price,c.name AS sku_name,#{item.buyCount} AS buy_count,#{item.istatus} AS istatus,now() AS create_date FROM spu AS b LEFT JOIN sku AS c ON b.id=c.spu_id WHERE c.id=#{item.skuId} and c.del_flag='0') AS tb
		</foreach>
	</insert>
      
</mapper>

springboot测试类

@RunWith(SpringRunner.class)
@SpringBootTest(classes= {ApiApplication.class})
public class AppTest {

    @Autowired
    private ShopcartMapper shopcartMapper;
    
    @Test
    public void testInsertBatchByselectFrom() {
        final ArrayList<Shopcart> shopcartDatas = new ArrayList<Shopcart>() {{
            for (int i = 1; i < 7; i++) {
                add(new Shopcart(1L, (long) i, i, "1"));
            }
        }};

        shopcartMapper.insertBatch(shopcartDatas);
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值