【MyBatis使用】 mapper文件未编译 + statementType使用 + 返回结果字段顺序不一致 + 获取自增ID + 一个update标签批量更新记录
1. mapper 文件未編譯
如果mapper文件未編譯,會(huì)報(bào)綁定異常。
<build><resources><resource><directory>src/main/java</directory><includes><include>**/*.xml</include></includes><filtering>false</filtering></resource></resources> </build>2. statementType
使用 statementType 標(biāo)記操作 SQL 的對(duì)象取值說(shuō)明。注意:如果只為STATEMENT,那么 SQL 就是直接進(jìn)行的字符串拼接,如果是字符串則需要【自行加上引號(hào)】如果為PREPARED,是使用的參數(shù)替換,也就是索引占位符, # 會(huì)轉(zhuǎn)換為 ? 再設(shè)置對(duì)應(yīng)的參數(shù)的值。
【STATEMENT】直接操作SQL,不進(jìn)行預(yù)編譯,使用($)獲取數(shù)據(jù)。
<update id="xxx" statementType="STATEMENT">update car set price=${price} where id=${id} </update>【PREPARED】【不傳遞 statementType 值時(shí)的默認(rèn)值】預(yù)處理參數(shù),進(jìn)行預(yù)編譯,使用(#)獲取數(shù)據(jù)。
<update id="xxx" statementType="PREPARED">update car set car_number=#{carNumber} where id=#{id} </update>【CALLABLE】執(zhí)行存儲(chǔ)過(guò)程。
<select id="xxx" statementType="CALLABLE">{call PROCEDURE_NAME()} </select>$ 與 # 混用時(shí)會(huì)有報(bào)錯(cuò),具體原因暫未探究。
3. 返回map時(shí),key與select的字段順序不一致
將 Hashmap 換成 LinkedHashMap 即可【順序是否有意義要看業(yè)務(wù)是否需要了】
<select id="xxx" resultType="java.util.HashMap"> <select id="xxx" resultType="java.util.LinkedHashMap">4. 獲取自增ID
我們可以自己獲取當(dāng)前的自增ID,這個(gè)顯然是有并發(fā)問(wèn)題的:
SELECTauto_increment FROMinformation_schema.`TABLES` WHEREtable_name = 'tableName' AND TABLE_SCHEMA = 'schemaName'5. 一個(gè)update標(biāo)簽中執(zhí)行多條update語(yǔ)句
MySql默認(rèn)是不支持的,但是并不代表不能實(shí)現(xiàn),只需要在jdbc的配置文件中添加 allowMultiQueries=true 這個(gè)配置即可:
url: jdbc:mysql://localhost:3306/test?allowMultiQueries=true username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver然后在映射文件中的標(biāo)簽下將多條sql用;隔開即可,示例代碼:
<update id="updateBatchSingle" parameterType="java.util.List"><foreach collection="list" item="item" index="index" open="" close=";" separator=";">update user<set>status = #{item.status}</set>where id = #{item.id}</foreach> </update>總結(jié)
以上是生活随笔為你收集整理的【MyBatis使用】 mapper文件未编译 + statementType使用 + 返回结果字段顺序不一致 + 获取自增ID + 一个update标签批量更新记录的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 【Java代码】使用双冒号 :: 简洁代
- 下一篇: Nexus【环境搭建 01】CentOS