MyBatis-SQL语句设置多个参数的方法

概述

mybatis SQL语句设置多个参数的方法一共有三种:
1.散装的参数,需要使用@Param(“sql中参数占位符名称”)。
2.实体类封装参数,需保证SQL中的参数名能够对上实体类属性名。
3.map集合,需保证SQL中的参数名能够对上map集合的键名称。

方法一:散装参数

dao层接口

@Mapper
public interface UserMapper {

    List<User> getMatchCount(String username, String password);
}

UserMapper.xml中对应的mapper

<select id="getMatchCount" resultType="User">
        select *
        from sys_user
        where username=#{username} and password=#{password};
</select>

这里有一个点要注意,如果接口方法中的参数与sql中的参数名不同的话,需要@Param指定参数

@Mapper
public interface UserMapper {

    List<User> getMatchCount(@Param("username") String n, @Param("password") String p);
}

方法二:实体类封装参数

假如需要传入的参数较多,可以使用一个pojo类封装参数,同时要注意实体类属性名能够对上SQL中的参数名。

@Mapper
public interface UserMapper {
    List<User> getMatchCount2(@Param("param") ParamClass param);
}

这里使用了ParamClass一个普通的pojo类来封装参数。

    <select id="getMatchCount2" resultType="User">
        select *
        from sys_user
        where username=#{param.username} and password=#{param.password};
    </select>

方法三:map集合

也可以使用map,需保证SQL中的参数名能够对上map集合的键名称。

@Mapper
public interface UserMapper {
    List<User> getMatchCount3(Map<String, String> map);
}
    <select id="getMatchCount3" resultType="User">
        select *
        from sys_user
        where username=#{u} and password=#{p};
    </select>
    @Test
    public void testGetMatchCount3(){
        HashMap<String, String> map = new HashMap<>();
        map.put("u", "zou");
        map.put("p", "123");
        List<User> list = userMapper.getMatchCount3(map);
        System.out.println("list大小:"+list.size());
    }

在这里插入图片描述

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值