批量添加的sql Java mybatis
在Java MyBatis中,可以使用批量添加的方法insertList来实现批量插入数据。
首先,在Mapper接口中定义批量插入的方法:
public interface YourMapper {
void insertList(List<YourObject> list);
}
然后,在对应的Mapper XML文件中实现该方法:
<insert id="insertList" parameterType="java.util.List">
INSERT INTO your_table (column1, column2, ...) VALUES
<foreach collection="list" item="item" separator=",">
(#{item.property1}, #{item.property2}, ...)
</foreach>
</insert>
其中,YourObject是需要插入的对象类,your_table是需要插入数据的表名,column1, column2, ...是表的列名,property1, property2, ...是对象的属性名。
最后,在Java代码中调用该方法进行批量插入:
List<YourObject> list = new ArrayList<>();
// 添加需要插入的对象到list中
YourMapper mapper = sqlSession.getMapper(YourMapper.class);
mapper.insertList(list);
sqlSession.commit();
注意,在调用insertList方法后需要手动调用commit()方法来提交事务
原文地址: http://www.cveoy.top/t/topic/iZNi 著作权归作者所有。请勿转载和采集!