使用MyBatis的話,它幫你生成的方法一般只是單條操作,如果要查詢或者插入大量的數據時用for的話顯然效率很低,所以要通過自定義Mapper方法和foreach標簽來寫sql語句
首先要滿足以下條件
- 配置好generatorConfig.xml
- 安裝了MyEclipse和MyBatis-Generator插件
- 懂得sql語句
首先要新建一張表
在generatorConfig.xml插入
tableName填你新建的表名,domainObjectName填你所要自動生成的領域類名
<table tableName="表名" domainObjectName="類名"></table>
整體如下
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<!-- 驅動包 -->
<!--要用本地jar包路徑-->
<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">
<!-- mybatis基礎屬性配置 -->
<!-- 數據庫連接 -->
<!-- model的配置 -->
<!--mybatis的xml的配置 -->
<!--mapper的配置 -->
<!--其他表名 -->
<table tableName="chat_history" domainObjectName="ChatHistory"></table>
</context>
</generatorConfiguration>
然后用MyEclipse的MyBatis-Generator
右鍵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<ChatHistory> list);
}
修改相應的mapper.xml
添加上如下代碼
<!--id是自定義的方法名,parameterType是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
<!--item就是List里每一項的對象名,要用","分割每一條數據,最后要";"結尾-->
<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>