MyBatis传递多个参数方法

一、MyBatis传递多个参数方法

1.使用Map传递参数

 <select id="selByMapPage" parameterType="map" resultType="yuan.yuanmybatis.entity.Account">
       select id,name,created,updated from account where name like concat('%',#{name},'%') limit ${offset},${pagesize}
    </select>

对于AccountDao接口

List<Account> selByMapPage(Map<String,String> params);

测试

    @Test
    public void contextLoads() {
        Map<String,String> map=new HashMap<>();
        map.put("offset","0");
        map.put("pagesize","3");
        map.put("name","张");
        List<Account> list=accountMapper.selByMapPage(map);
        for (Account a:list){
            System.out.println(a.getName());
        }
    }

2.使用注解@Param传递参数

   <select id="selByIndexPage" resultType="yuan.yuanmybatis.entity.Account">
       select id,name,created,updated from account limit #{offset},#{pagesize}
    </select>

对于AccountDao接口

 List<Account> selByIndexPage(@Param("offset") int offset,@Param("pagesize") int pagesize);

3.使用JavaBean传递参数

 <select id="selByJavaBeanPage" parameterType="yuan.yuanmybatis.mapper.AccountParams" resultType="yuan.yuanmybatis.entity.Account">
       select id,name,created,updated from account where name like concat('%',#{name},'%') limit ${offset},${pagesize}
    </select>

新建一个参数类

public class AccountParams {
    private String name;
    private Integer offset;
    private Integer pagesize;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getOffset() {
        return offset;
    }

    public void setOffset(Integer offset) {
        this.offset = offset;
    }

    public Integer getPagesize() {
        return pagesize;
    }

    public void setPagesize(Integer pagesize) {
        this.pagesize = pagesize;
    }
}

对于AccountDao接口

List<Account> selByJavaBeanPage(AccountParams accountParams);

测试代码

 @Test
    public void contextLoads() {
        AccountParams accountParams=new AccountParams();
        accountParams.setName("张");
        accountParams.setOffset(0);
        accountParams.setPagesize(3);
        List<Account> list=accountMapper.selByJavaBeanPage(accountParams);
        for (Account a:list){
            System.out.println(a.getName());
        }
    }

二、总结

1.使用Map传递参数,对于可读性比较差,后期维护和扩展不友好,应该减少使用这种方式传递参数。

2.使用@Param注解传递参数,当参数少于5个的时候,比较推荐,因为比较直观,方便。

3.使用javaBean传递参数,当参数比较多的时候,建议使用这种方式。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值