在MyBatis中,可以使用批量操作來(lái)大批量存儲(chǔ)數(shù)據(jù)。以下是一種實(shí)現(xiàn)方式:
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">
<!-- 數(shù)據(jù)源配置 -->
</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<>();
// 添加要插入的數(shù)據(jù)到dataList
mapper.batchInsert(dataList);
session.commit();
} finally {
session.close();
}
}
}
通過(guò)以上步驟,就可以實(shí)現(xiàn)MyBatis的大批量存儲(chǔ)數(shù)據(jù)功能。注意,在實(shí)際使用中,還可以根據(jù)具體需求對(duì)配置進(jìn)行調(diào)整和優(yōu)化,以提高插入數(shù)據(jù)的效率。