在MyBatis中,可以使用批量操作来大批量存储数据。以下是一种实现方式:
public interface MyMapper {
@Insert("INSERT INTO my_table (column1, column2) VALUES (#{item.field1}, #{item.field2})")
void batchInsert(List<MyData> dataList);
}
public class MyData {
private String field1;
private String field2;
// getter and setter
}
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<!-- 数据源配置 -->
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="my_mapper.xml"/>
</mappers>
<settings>
<setting name="jdbcTypeForNull" value="NULL"/>
<setting name="cacheEnabled" value="true"/>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
</settings>
</configuration>
<mapper namespace="com.example.MyMapper">
<insert id="batchInsert" parameterType="java.util.List">
<foreach collection="list" item="item" separator=";">
INSERT INTO my_table (column1, column2) VALUES (#{item.field1}, #{item.field2})
</foreach>
</insert>
</mapper>
public class Main {
public static void main(String[] args) {
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlSessionFactory.openSession();
try {
MyMapper mapper = session.getMapper(MyMapper.class);
List<MyData> dataList = new ArrayList<>();
// 添加要插入的数据到dataList
mapper.batchInsert(dataList);
session.commit();
} finally {
session.close();
}
}
}
通过以上步骤,就可以实现MyBatis的大批量存储数据功能。注意,在实际使用中,还可以根据具体需求对配置进行调整和优化,以提高插入数据的效率。