使用的数据库自增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);
}
}