MyBatis获取参数值的方式

本文详细介绍了在MyBatis中获取不同类型参数值的方法,包括单个字面量、多个字面量、Map类型、实体类型参数以及使用@Param注解的方式。针对每种方式,分别展示了接口方法定义、映射文件中的SQL写法,并强调了注意事项,如使用#{}与${}的区别,以及在处理多个参数时的键值规则。

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

1、单个字面量类型的参数

此时可以使用KaTeX parse error: Expected 'EOF', got '#' at position 4: {}和#̲{}以任意的名称获取参数的值,…{}需要手动加单引号

<select id="getUserByName" resultType="com.lucky.pojo.User">
        <!--select * from t_user where username=#{username}-->
         <!--select * from t_user where username=#{eee}-->
        select * from t_user where username= '${eee}'
    </select>

如果使用 ,必须 加 ′ ′ ,不然 M y b a t i s 会将参数解析为列名。因为 , 必须加'', 不然Mybatis会将参数解析为列名。因为 ,必须′′,不然Mybatis会将参数解析为列名。因为的本质是字符串拼接。#的本质是占位符。

2、多个字面量类型的参数

mapper接口中的方法,有两个参数

 User checkLogin(String name, String password);

如果在映射文件中直接使用参数名称

 <select id="checkLogin" resultType="com.lucky.pojo.User">
       select * from t_user where username= #{username} and password= #{password}
    </select>

这时候会报错,参数username不可用,可用参数为 [arg1, arg0, param1, param2]
在这里插入图片描述因此映射文件中,sql语句的正确写法为:

   <select id="checkLogin" resultType="com.lucky.pojo.User">
       select * from t_user where username= #{param1} and password= #{param2}
    </select>

当方法有多个输入参数时,此时MyBatis会自动将这些参数放在一个map集合中,以arg0,arg1…为键,以参数为值;以param1,param2…为键,以参数为值;因此只需要通过${}和#{}访问map集合的键就可以获取相对应的参数取值。

3、Map类型参数

若mapper接口中的方法需要的参数为多个时,此时可以手动创建map集合,将这些数据放在map中。
查询方法定义

User checkLogin2(Map<String, String> params);

映射文件sql写法

 <select id="checkLogin2" resultType="com.lucky.pojo.User">
       select * from t_user where username= #{username} and password= #{password}
    </select>

4、实体类型参数

若mapper接口中的方法参数为实体类对象时
此时可以使用KaTeX parse error: Expected 'EOF', got '#' at position 4: {}和#̲{},通过访问实体类对象中的属…{}需要手动加单引号。
mapper方法定义

int insertUser(User user);

映射文件sql定义

 <insert id="insertUser">
            insert into t_user values(null,#{username}, #{password}, #{age}, #{gender}, #{email})
    </insert>

5、使用@Param标识参数

mapper中方法定义时,给参数加上@param注解,注解参数为xml文件中使用的参数名称

 User checkLogin3(@Param("name") String name, @Param("pwd") String password);

xml文件中sql语句定义

<select id="checkLogin3" resultType="com.lucky.pojo.User">
       select * from t_user where username= #{name} and password= #{pwd}
    </select>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值