需要用到foreach标签
<insert id="batchInsert" parameterType="java.util.List">
insert into your_table (id, status, common_property, list_property)
values
<foreach collection="list" item="item" separator=",">
(
#{item.id},
#{item.status},
#{item.commonProperty},
<foreach collection="item.listProperty" item="listItem" separator=",">
#{listItem}
</foreach>
)
</foreach>
</insert>
列数和插入值数量不一样怎么办:
解决方法1:扁平化插入:将列表中的每个元素拆分成独立的插入操作。假设你的对象为 YourObject
,其中包含一个列表属性 listField
和其他属性,可以使用 MyBatis Plus 的动态 SQL 和 foreach 循环来实现扁平化插入,示例如下:
public void insertData(YourObject object) {
YourObject otherObject;
for (Object listItem : object.getListField()) {
otherObject = new YourObject();
otherObject.setListField(listItem);
otherObject.setOtherField1(object.getOtherField1());
otherObject.setOtherField2(object.getOtherField2());
// 设置其他属性...
yourMapper.insert(otherObject);
}
}
2.序列化插入:将整个对象序列化为 JSON 或其他适合存储的格式,并将其作为一个列插入到数据库中。在这种情况下,你只需要一个列来存储整个对象数据,无需拆分。
public void insertData(YourObject object) {
String json = convertObjectToJson(object); // 将对象转换为 JSON 字符串
yourMapper.insert(json);
}