mybatis 参数

# 和 $

  1. # 能避免 sql 注入 $ 不可以
  2. # 会自动根据类型处理,$ 直接拼接到 sql,意味着如果是引号不会加引号
  3. 关键字、表名、字段名、分页参数使用 $ 别的一律使用 #

sql 注入

select * from t_user where user username = ${name} 比如这个sql,如果参数是 zhangsan; delete from t_userlisi or 1=1 就 gg

为什么 $ 不能防止注入?

# 参数会被处理成占位符,jdbc 会处理占位符

$ 参数直接拼接到 sql,没有占位符,jdbc 就不会处理这个参数

单参数

用不用 @Param 注解都行,但是取值的时候要注意参数是值还是对象,如下:

// select * from t_user where name = #{username}
User findByUser(User user);

// select * from t_user where name = #{user.username}
User findByUser(@Param('user') User user);

多参数

每个参数都要使用 @Param 修饰,不然就是用下标形势来取值

mapper 接口

 List<Account> selectBySearch(@Param("record") Account record, 
                              @Param("startDate") String startDate, 
                              @Param("endDate") String endDate, 
                              @Param("companyName") String companyName);

映射文件

<select id="selectBySearch" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from main_account
    where 1 = 1
    <!-- 使用参数 1 (是个对象) -->
    <if test="record.email != null">
        and email = #{record.email}
    </if>
    <!-- 使用参数 2 -->
    <if test="startDate != null">
        and create_date > str_to_date(concat('', #{startDate}),'%Y-%m-%d %H %i %s')
    </if>
    <!-- 使用参数 3 -->
    <if test="endDate != null">
        and create_date < str_to_date(concat('', #{endDate}),'%Y-%m-%d %H %i %s')
    </if>
    <!-- 使用参数 4 -->
    <if test="companyName != null">
        and (full_name like "%"#{companyName}"%" or short_name like "%"#{companyName}"%")
    </if>
</select>
posted @ 2023-07-28 11:27  CyrusHuang  阅读(12)  评论(0编辑  收藏  举报