Mybatis的传参注意点(单参数、多参数、复杂参数)

本文详细介绍了Mybatis在处理不同参数类型时的注意事项,包括List参数的使用,多个不同类型参数的传入,以及如何利用`useGeneratedKeys`和`keyProperty`获取自增主键。在List参数情况下,通过`<foreach>`标签遍历并结合resultMap进行映射。对于多参数,使用`@Param`注解区分参数。在主键自增场景下,设置`useGeneratedKeys=true`和`keyProperty`属性可以获取新插入记录的主键值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Mybatis的传参注意点(单参数、多参数、复杂参数)

1. 传入参数为List

mapper接口:

List<User> getUserList(List<Long> list);

mapper映射文件:List用foreach去遍历
如果查询的实体类的参数和数据库中的字段名不一致,要用resultMap进行映射

<select id="getUserList" resultMap="UserResultMap" parameterType="List">
        select * from user_info  where id in
        (
        <foreach collection="list" item="item" separator=",">
            #{item}
        </foreach>
        )
</select>

resultMap映射:column:数据库中的字段名,property:实体类中的属性名

<resultMap id="UserResultMap" type="User">
	    <!-- 定义主键 ,非常重要。如果是多个字段,则定义多个id -->
        <!-- property:主键在pojo中的属性名 -->
        <!-- column:主键在数据库中的列名 -->
        <id column="user_id" property="id" jdbcType="BIGINT"/>
        <!-- 定义其他属性 -->
        <result property="name" column="user_name" jdbcType="VARCHAR"/>
        <result property="createTime" column="create_time" jdbcType="DATE"/>
        <resul property="updateTime"t column="update_time" jdbcType="DATE"/>
</resultMap>

javaType和jdbcType的对应表:
在这里插入图片描述

2. 传入多个不同类型参数

mapper接口:

void updateAlarmInfo(@Param("user") User user,@Param("id") Long id);

mapper映射文件:传入多个参数时,parameterType不用写,在接口上写上参数的注解

<update id="updateUser" >
        update market_channel_alarm_info
        set update_time = sysDate(),
            name = #{user.name},
            status = '0'
        where id=#{id}
</update>

3. useGeneratedKeys和keyProperty的使用:

当主键是自增的情况下,添加一条记录的同时,其主键是不能使用的,但是有时我们需要该主键,这时我们只需要在其对应xml中加入以下属性即可:
useGeneratedKeys=“true” keyProperty=“对应的主键的对象”。

useGeneratedKeys这个只在insert语句中有效,当useGeneratedKeys为true时,如果插入的表id以自增列为主键时,将会把该自增id返回。例如:

<!-- 在主键是自增的情况下,添加成功后可以直接使用主键值,其中keyProperty的值是对象的属性值不是数据库表中的字段名-->
<insert id="addUser" parameterType="User" useGeneratedKeys="true" keyProperty="id">
        INSERT INTO market_channel_info(`user_name`, `user_gender`, `user_age`)
	    VALUES(#{name}, #{gender}, #{age})
</insert>

这样在之后的java代码中我们就可以获取该主键对应的对象的属性值(id)

### 传递参数的方式 在 MyBatis 中,可以通过多种方式实现参数的传递。以下是几种常见的传参方式及其具体实现: #### 1. 单个参数传递 当只需要传递单个参数时,可以直接将其作为方法参数的一部分。MyBatis 会自动识别并绑定该参数。 ```java public interface UserMapper { List<User> selectUsersByName(String name); } ``` 对应的 XML 映射文件如下: ```xml <select id="selectUsersByName" resultType="User"> SELECT * FROM users WHERE name LIKE CONCAT('%', #{name}, '%') </select> ``` 这里 `#{name}` 表示占位符,用于接收 Java 方法中的参数[^3]。 --- #### 2. 多个参数传递(使用注解) 如果需要传递多个参数,则可以借助 `@Param` 注解来区分不同的参数名称。 ```java public interface UserMapper { List<User> selectUsersByAgeAndName(@Param("age") int age, @Param("name") String name); } ``` XML 文件配置如下: ```xml <select id="selectUsersByAgeAndName" resultType="User"> SELECT * FROM users WHERE age = #{age} AND name LIKE CONCAT('%', #{name}, '%') </select> ``` 这种方式适用于简多参数场景。 --- #### 3. 使用 Map 类型传递参数 对于复杂的查询条件或者不确定数量的参数,可以使用 `Map` 来封装所有的键值对。 Java 接口定义: ```java public interface UserMapper { List<User> selectUsersByConditions(Map<String, Object> params); } ``` 调用时: ```java Map<String, Object> paramMap = new HashMap<>(); paramMap.put("age", 20); paramMap.put("name", "John"); List<User> userList = userMapper.selectUsersByConditions(paramMap); ``` XML 配置: ```xml <select id="selectUsersByConditions" resultType="User"> SELECT * FROM users <where> <if test="age != null">AND age = #{age}</if> <if test="name != null">AND name LIKE CONCAT('%', #{name}, '%')</if> </where> </select> ``` 这种动态 SQL 的写法非常灵活,适合复杂查询需求[^4]。 --- #### 4. 实体类对象传递 另一种常见的方式是将所有参数封装到一个实体类中,并直接将该对象作为参数传递给 Mapper 方法。 实体类定义: ```java @Data public class QueryCondition { private Integer age; private String name; } ``` 接口定义: ```java public interface UserMapper { List<User> selectUsersByEntity(QueryCondition condition); } ``` XML 配置: ```xml <select id="selectUsersByEntity" resultType="User"> SELECT * FROM users <where> <if test="condition.age != null">AND age = #{condition.age}</if> <if test="condition.name != null">AND name LIKE CONCAT('%', #{condition.name}, '%')</if> </where> </select> ``` 这种方法不仅结构清晰,还便于维护扩展[^5]。 --- #### 示例代码总结 以下是一个完整的例子,展示如何通过不同方式进行参数传递: ```java // 参数传递 List<User> singleParamResult = userMapper.selectUsersByName("Alice"); // 多参数传递 (带注解) List<User> multiParamResult = userMapper.selectUsersByAgeAndName(25, "Bob"); // 使用 Map 传递 Map<String, Object> mapParams = new HashMap<>(); mapParams.put("age", 30); mapParams.put("name", "Charlie"); List<User> resultMapFromMap = userMapper.selectUsersByConditions(mapParams); // 使用实体类传递 QueryCondition condition = new QueryCondition(); condition.setAge(35); condition.setName("David"); List<User> resultMapFromEntity = userMapper.selectUsersByEntity(condition); ``` --- ### 总结 MyBatis 提供了丰富的参数传递机制,可以根据实际业务需求选择合适的方式来处理各种复杂度的查询逻辑。无论是简还是复杂的查询条件,都可以找到一种优雅的解决方案[^1]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值