在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的大批量存儲數據功能。注意,在實際使用中,還可以根據具體需求對配置進行調整和優化,以提高插入數據的效率。