MyBatis四:MyBatis获取参数的两种方式

MyBatis获取参数的两种方式

一、引入
  1. 从浏览器中发送来的数据,要通过service传输到xxxMapper.xml映射文件中,那么Mapper映射文件要如何来获取传输来的参数,来实现SQL语句的拼接呢。

  2. MyBatis获取参数的两种方式

    ${}:本质是字符串拼接
    
    #{}:本质是填充占位符
    
二、MyBatis获取参数值的各种情况
  1. mapper接口方法的参数为单个的字面量类型

    可以通过KaTeX parse error: Expected 'EOF', got '#' at position 5: { }和#̲{ }**,在**大括号内写入…{ }的单引号问题

    public interface ParamMapper {
         
         
        // 根据用户名查询人员信息
        User getUserByName(String username);
    }
    
    // 注意:真实代码中,两个方式只能写一种
    <mapper namespace="com.atguigu.mybatis.mapper.ParamMapper">
        <select id="getUserByName" resultType="User">
            // 方式一
            select * from t_user where username = #{
         
         username}
    		// 方式二
    		select * from t_user where username = '${
         
         username}'
        </select>
    </mapper>
    
  2. mapper接口有多个参数

    此时在框架底层,MyBatis会将这些参数放在一个map集合中,以下述两种方式进行存储

    方式1:以arg0,arg1,…为键,以参数为值

    方式2:以param1,param2,…为键,以参数为值

    故,在#{ }和${ }内放入的是上述两种键名称,不可以是其它的

    <mapper namespace="com.atguigu.mybatis.mapper.ParamMapper">
        <select id="checkLogin" resultType="user">
            select * from t_user where username = #{
         
         arg0} and pwd = #{
         
         arg1}
        </select>
    </mapper>
    
  3. mapper接口有多个参数

    可以手动将这些参数放在一个map中存储,然后将map中的键放在#{ }内

    mapper接口
    public interface ParamMapper {
         
         
        User checkLoginByMap(Map<String,Object> map);
    }
    
    映射文件
    <mapper namespace="com.atguigu.mybatis.mapper.ParamMapper">
        <select id="checkLoginByMap" resultType="user">
            select * from t_user where username = #{username} and pwd = #{password}
        </select>
    </mapper>
    
    测试程序
    public class ParamTest {
         
         
        @Test
        public void test4() {
         
         
            SqlSession sqlSession = SqlSessionUtils.getSqlSession();
            ParamMapper mapper = sqlSession.getMapper(ParamMapper.class);
            Map<String, Object> map = new HashMap<>();
            map.put("username","李四");
            map.put("password","123456");
            User userByName = mapper.checkLoginByMap(map);
            System.out.println("userByName = " + userByName);
        }
    }
    
  4. mapper接口参数是一个实体类对象

    只需要通过#{ } 和 ${ },以属性发的方式访问属性值即可。

    mapper接口
    public interface ParamMapper {
         
         
        int insertUser(User user);
    }
    
    mapper映射文件
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

e_nanxu

感恩每一份鼓励-相逢何必曾相识

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值