Mybatis常见入参方式(Map、注解、JavaBean)

发布于:2022-11-06 ⋅ 阅读:(873) ⋅ 点赞:(0)

目录

1、使用Map传参;

2、使用注解传参;

3、使用JavaBean传参;

4、Mybatis使用#{}和${}注入参数的区别;


Mybatis给映射器传递多个参数分为以下三种方法。

1、使用Map传参;

  <select id="getUserByMy" parameterType="map">
    select user_name from tbl_user_infobymy where user_id in
    <foreach collection="ids" item="id" separator="," open="(" close=")">
        #{id}
    </foreach>
  </select>

dao层接口使用map作为入参

    UserInfo getUserByMy(Map<String, String> params);

调用dao层接口

Map<String, Object> map = HashMap<String, Object>();
String[] ids = {"12345", "12346"};
map.put("ids", ids);
getUserByMy();

2、使用注解传参;

使用 MyBatis 的注解 @Param() 传递参数

  <select id="getUserByMy" parameterType="map">
    select user_name from tbl_user_infobymy where user_id = #{params.id}
  </select>

dao层接口使用map作为入参;

 UserInfo getUserByMy(@Param("params")Map<String, String> map);

把参数传递给后台时,MyBatis 通过 @Param 提供的名称就会知道 #{name} 代表 name 参数,提高了参数可读性。 

3、使用JavaBean传参;

在参数过多的情况下,MyBatis 允许组织一个 JavaBean;

    int updateByPrimaryKey(UserInfo record);
  <update id="updateByPrimaryKey" parameterType="com.demo.projo.UserInfo">
    update tbl_user_infobymy
    set user_name = #{userName,jdbcType=VARCHAR},
      user_psd = #{userPsd,jdbcType=VARCHAR}
    where user_id = #{userId,jdbcType=INTEGER}
  </update>
userName,userPsd,userId对应JavaBean实体类UserInfo的属性值;

4、Mybatis使用#{}和${}注入参数的区别;

使用#{}方式:

#{}将传入的数据都当成一个字符串,会对自动传入的数据加一个双引号。如:order by #{user_id},如果传入的值是111,那么解析成sql时的值为order by "111", 如果传入的值是id,则解析成的sql为order by "id".

#方式能够很大程度防止sql注入,相当于使用PreparedStatement方式

使用${}方式:

${}将传入的数据直接显示生成在sql中。如:order by ${user_id},如果传入的值是111,那么解析成sql时的值为order by user_id,  如果传入的值是id,则解析成的sql为order by id.

$方式无法防止SQL注入,如在登录查询用户时,若使用${}方式传参,当密码为upass='' or 1=1时,密码是任意字符时,返回的结果都为true;

select * from user where uname='user1' and upass='' or 1=1;