使用MyBatis的话,它帮你生成的方法一般只是单条操作,如果要查询或者插入大量的数据时用for的话显然效率很低,所以要通过自定义Mapper方法和foreach标签来写sql语句
首先要满足以下条件
在generatorConfig.xml插入
tableName填你新建的表名,domainObjectName填你所要自动生成的领域类名
<table tableName="表名" domainObjectName="类名">table>
整体如下
<generatorConfiguration>
<classPathEntry location="D:\maven\backend_repository\repository\mysql\mysql-connector-java\5.1.35\mysql-connector-java-5.1.35.jar" />
<context id="MySqlTables" targetRuntime="MyBatis3" introspectedColumnImpl="com.bola.nwcl.common.mybatis.generator.SimpleIntrospectedColumn">
<table tableName="chat_history" domainObjectName="ChatHistory">table>
context>
generatorConfiguration>
右键generatorConfig.xml,生成相应的Model(表中属性),Example(查询规则),Mapper(可以在这自定义方法),mapper.xml(自定义方法用sql语句实现)
现在只关注Mapper和mapper.xml
因为MyBatis原来的mapper没有提供一次插入多条数据的方法,所以要在Mapper里自定义一个方法,如
public interface ChatHistoryMapper extends Mapper<ChatHistory, ChatHistoryExample, Long> {
void insertChatHistoryList(List list);
}
添加上如下代码
<insert id="insertChatHistoryList" useGeneratedKeys="true" parameterType="java.util.List">
<selectKey resultType="long" keyProperty="id">
SELECT LAST_INSERT_ID()
selectKey>
insert into n_chat_history (id,from_name,to_name,message_type, content)
values
<foreach collection="list" item="item" index="index" separator="," close=";">
(#{item.id,jdbcType=BIGINT}, #{item.fromName,jdbcType=VARCHAR}, #{item.toName,jdbcType=VARCHAR}, #{item.content,jdbcType=VARCHAR},
#{item.sendType,jdbcType=INTEGER})
foreach>
insert>