mybatis参数名

362 阅读2分钟
原文链接: my.oschina.net

Mybatis 入参方式

单个基本类型或String参数

在mapper文件中随便写

<select id="" resultMap="resultMap">
select * from USER_INFO t where t.name = #{sdfa,jdbcType=VARCHAR}
</select>
List<Student> get(String name);

单个Map或者自定义类型的

  1. 如是Map ,那么参数各是Map的key
  2. 如果是自定义类型的,参数是属性名,更确切的说是get方法,例如:getName(),那么mapper文件中就要写#{name,jdbcType=VARCHAR}

如果是单个的Collection

参数名字就是collection

<select id="" resultMap="resultMap">
select * from USER_INFO t where t.name in 
    <foreach collection="conllection" item="i" ......>
    </foreach>
</select>
List<Student> get(List<String> names);

如果是多个参数

  1. 可以使用 @Param("parametername")

    <select id="" resultMap="resultMap">
    select * from USER_INFO t where t.name in 
        <foreach collection="param" item="i" ......>
        </foreach>
        and age = #{age,jdbcType=NUMERIC}
    </select>
    
    List<Student> get(@Param("param") List<String> names,@Param("age") int age);
    
  2. 如果不想使用@Param,而是想直接使用接口方法参数的变量名作为mapper的参数名,需要增加 编译参数 -parameters,并启用 useActualParamName 选项(默认开启)来编译项目这里以maven为例

    普通工程

     <build>
         <plugins>
             <plugin>
                 <groupId>org.apache.maven.plugins</groupId>
                 <artifactId>maven-compiler-plugin</artifactId>
                 <version>3.8.1</version>
                 <configuration>
                     <target>1.8</target>
                     <source>1.8</source>
                     <parameters>true</parameters>
                 </configuration>
             </plugin>
         </plugins>
     </build>
    

    springboot:

    <plugin>
    				<groupId>org.springframework.boot</groupId>
    				<artifactId>spring-boot-maven-plugin</artifactId>
    				<configuration>
    					<jvmArguments>-parameters</jvmArguments><!--  增加这个参数 -->
    				</configuration>
    			</plugin>
    

    如上设置好之后 ,就可以直接用接口方法参数名作为mapper参数了

    接口文件中:

    List<ComBusinessSwitch> getSwitchByCode(String code, String orgId, String stationId);
    

    mapper文件中

    <select id="getSwitchByCode" resultMap="BaseResultMap">
    select * from SWITCH T where code = #{code,jdbcType=VARCHAR} and orgid = #{orgId,jdbcType=VARCHAR} and stationid = #{stationId,jdbcType=VARCHAR}
    </select>