mybatis 3.4.1之后,允許不加 @Param指定參數名稱,自動會以入參的名稱作為param key
useActualParamName
允許使用方法簽名中的名稱作為語句參數名稱。
為了使用該特性,你的項目必須采用 Java 8 編譯,並且加上 -parameters 選項。(新增於 3.4.1)
默認:true
案例
不加 @Param 的多入參mapper
public interface TestUserMapper {
int update(Long guid, String appName);
}
入參為: update(110, "testAppName")
- 編譯時不加 -parameters 參數,那么mybatis的參數的格式是
{"arg0":110, "arg1":"testAppName"}
, 在xml文件就不能用 #{guid} 來取值了 - 加上 -parameters 編譯后,參數格式為
{"guid":110, "appName":"testAppName"}
在xml sql中就能正常使用參數名稱
原理:
useActualParamName 默認是true,如果入參沒加@Param指定參數key,則會利用java8的特性,從反射類Parameter#getName()獲取這個參數的名稱
例如,可以maven編譯插件上指定
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>8</source>
<target>8</target>
<compilerArgs>
<arg>-verbose</arg>
<arg>-Xlint:all</arg>
**<arg>-parameters</arg>**
</compilerArgs>
</configuration>
</plugin>
結論
不推薦偷懶,這種方式依賴java8的編譯特性,比較隱晦,容易讓其他開發混淆