SPRINGBOOT整合MYBATIS传参的几种方式

SPRINGBOOT整合MYBATIS传参的几种方式(多参数传递)

标签: SpringBoot整合Mybatis  Mybatis传递多个参数  MyBatis的传入参数parameterType类型

在SpringBoot整合Mybatis中,传递多个参数的方式和Spring整合Mybatis略微有点不同,下面主要总结三种常用的方式

一、顺序传参法 
Mapper层: 
传入需要的参数

public interface GoodsMapper {

 

    public Goods selectBy(String name,int num);        

}

  • 1
  • 2
  • 3
  • 4

Mapper.xml: 
*使用这种方式,在SpringBoot中,参数占位符用#{arg0},#{arg1},#{arg…} 
 
总结:这种方法不建议使用,sql层表达不直观,且一旦顺序调整容易出错。

二、@Param注解传参法 
Mapper层:

public interface GoodsMapper {

 

    public Goods selectBy(@Param("name")String name,@Param("num")int num);

 

}

  • 1
  • 2
  • 3
  • 4
  • 5

Mapper.xml: 
*#{}里面的名称对应的是注解@Param括号里面修饰的名称。

<select id="selectBy" resultMap="BaseResultMap">

    select

    <include refid="Base_Column_List" />

    from goods

    where good_name=#{name} and good_num=#{num}

</select>

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

总结:这种方法在参数不多的情况还是比较直观的,推荐使用。

三、使用Map封装参数 
Mapper层: 
将要传入的多个参数放到Map集合

public interface GoodsMapper {

 

    public Goods selectBy(Map map);

}

  • 1
  • 2
  • 3
  • 4

Mapper.xml: 
*#{}里面的名称对应的是Map里面的key名称

<select id="selectBy" resultMap="BaseResultMap">

    select

    <include refid="Base_Column_List" />

    from goods

    where good_name=#{name} and good_num=#{num}

</select>

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

总结:这种方法适合传递多个参数,且参数易变能灵活传递的情况。

Service层: 
带上要传入的参数

public interface GoodsService {

 

    public Goods selectBy(String name,int num);

}

  • 1
  • 2
  • 3
  • 4

Service接口实现层: 
封装Map集合:

@Override

public Goods selectBy(String name,int num) {

    Map<String, String> map = new HashMap<String, String>();

    map.put("name",name);

    map.put("num",num+"");

    return  GoodsMapper.selectBy(map);

}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

Controller层:

@RequestMapping("/selectBy.do")

@ResponseBody

public Goods selectBy(String name,int num) {

 

        return  goodsService.selectBy(name,num);

}

 

posted @ 2022-02-10 21:18  風色  阅读(337)  评论(0)    收藏  举报