mybatis动态SQL防止SQL注入


IvrNodeTreeMapper.java如下:

package com.example.springbootannotationmybatis.mapper;


import com.example.springbootannotationmybatis.domain.IvrNodeTree;
import com.example.springbootannotationmybatis.sqlprovider.IvrNodeTreeSqlProvider;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.type.JdbcType;

import java.util.Date;
import java.util.List;

/**
 * Title: IvrNodeTreeMapper
 * Description: IvrNodeTreeMapper
 * Date:  2018/5/17
 *
 * @author <a href=mailto:[email protected]>chaochao</a>
 */
@Mapper
public interface IvrNodeTreeMapper {

    @InsertProvider(type = IvrNodeTreeSqlProvider.class, method = "batchInsert")
    boolean addBatch(List<IvrNodeTree> ivrNodeTrees);

    //不能防止SQL注入
    @SelectProvider(type = IvrNodeTreeSqlProvider.class,method = "queryTopDanger")
    @Results(value = {
            @Result(id = true, property = "id", column = "id", javaType = Long.class, jdbcType = JdbcType.BIGINT),
            @Result(id = false, property = "ivrFlag", column = "ivr_flag", javaType = String.class, jdbcType = JdbcType.VARCHAR),
            @Result(id = false, property = "customerType", column = "customer_type", javaType = Integer.class, jdbcType = JdbcType.INTEGER),
            @Result(id = false, property = "businessType", column = "business_type", javaType = Integer.class, jdbcType = JdbcType.INTEGER),
            @Result(id = false, property = "treeContent", column = "tree_content", javaType = String.class, jdbcType = JdbcType.LONGVARCHAR),
            @Result(id = false, property = "signature", column = "signature", javaType = String.class, jdbcType = JdbcType.VARCHAR),
            @Result(id = false, property = "versionTimestamp", column = "version_timestamp", javaType = Date.class, jdbcType = JdbcType.DATE),})
    List<IvrNodeTree> queryTopDanger(String ivrFlag, Integer customerType, Integer businessType, String endTimestamp, int count);


    //可以解决SQL注入
    @SelectProvider(type = IvrNodeTreeSqlProvider.class,method = "queryRecentTop")
    @Results(value = {
            @Result(id = true, property = "id", column = "id", javaType = Long.class, jdbcType = JdbcType.BIGINT),
            @Result(id = false, property = "ivrFlag", column = "ivr_flag", javaType = String.class, jdbcType = JdbcType.VARCHAR),
            @Result(id = false, property = "customerType", column = "customer_type", javaType = Integer.class, jdbcType = JdbcType.INTEGER),
            @Result(id = false, property = "businessType", column = "business_type", javaType = Integer.class, jdbcType = JdbcType.INTEGER),
            @Result(id = false, property = "treeContent", column = "tree_content", javaType = String.class, jdbcType = JdbcType.LONGVARCHAR),
            @Result(id = false, property = "signature", column = "signature", javaType = String.class, jdbcType = JdbcType.VARCHAR),
            @Result(id = false, property = "versionTimestamp", column = "version_timestamp", javaType = Date.class, jdbcType = JdbcType.DATE),})
    List<IvrNodeTree> queryTop(@Param("ivrFlag") String ivrFlag, @Param("customerType") Integer customerType, @Param("businessType") Integer businessType, @Param("endTimestamp") String endTimestamp, @Param("count") int count);


    @Select("select COUNT(*) from ivr_node_tree where signature=#{signature}")
    int findSignature(String signature);
}


IvrNodeTreeSqlProvider.java

package com.example.springbootannotationmybatis.sqlprovider;

import com.example.springbootannotationmybatis.domain.IvrNodeTree;
import org.apache.ibatis.jdbc.SQL;
import org.springframework.util.StringUtils;

import java.text.MessageFormat;
import java.util.List;
import java.util.Map;

/**
 * Title: IvrNodeTreeSqlProvider
 * Description: IvrNodeTreeSqlProvider
 * Date:  2018/5/17
 *
 * @author <a href=mailto:[email protected]>chaochao</a>
 */

public class IvrNodeTreeSqlProvider {

    private String TABLE_NAME = "ivr_node_tree";

    public String batchInsert(Map<String, List<IvrNodeTree>> map) {
        List<IvrNodeTree> list = map.get("list");
        StringBuilder sb = new StringBuilder();
        sb.append("insert into ");
        sb.append(TABLE_NAME);
        sb.append(" (ivr_flag,customer_type,business_type,tree_content,signature,version_timestamp)");
        sb.append(" values ");
        MessageFormat mf = new MessageFormat(
                "(#'{'list[{0}].ivrFlag},#'{'list[{0}].customerType},#'{'list[{0}].businessType},"
                        + "#'{'list[{0}].treeContent},#'{'list[{0}].signature},#'{'list[{0}].versionTimestamp})");
        for (int i = 0; i < list.size(); i++) {
            sb.append(mf.format(new Object[] { i }));
            if (i < list.size() - 1) {
                sb.append(",");
            }
        }

        //insert into ivr_node_tree (ivr_flag,customer_type,business_type,tree_content,signature,version_timestamp) values (#{list[0].ivrFlag},#{list[0].customerType},#{list[0].businessType},#{list[0].treeContent},#{list[0].signature},#{list[0].versionTimestamp}),(#{list[1].ivrFlag},#{list[1].customerType},#{list[1].businessType},#{list[1].treeContent},#{list[1].signature},#{list[1].versionTimestamp}),(#{list[2].ivrFlag},#{list[2].customerType},#{list[2].businessType},#{list[2].treeContent},#{list[2].signature},#{list[2].versionTimestamp}),(#{list[3].ivrFlag},#{list[3].customerType},#{list[3].businessType},#{list[3].treeContent},#{list[3].signature},#{list[3].versionTimestamp}),(#{list[4].ivrFlag},#{list[4].customerType},#{list[4].businessType},#{list[4].treeContent},#{list[4].signature},#{list[4].versionTimestamp}),(#{list[5].ivrFlag},#{list[5].customerType},#{list[5].businessType},#{list[5].treeContent},#{list[5].signature},#{list[5].versionTimestamp})
        System.out.println(sb.toString());
        return sb.toString();
    }


    /**
     * 拼接字符串,不能防止SQL注入,有风险
     * @param ivrFlag
     * @param customerType
     * @param businessType
     * @param endTimestamp
     * @param count
     * @return
     */
    public String queryTopDanger(String ivrFlag, Integer customerType, Integer businessType, String endTimestamp, int count) {

        SQL sql = new SQL().SELECT("*").FROM(TABLE_NAME);
        if (StringUtils.hasText(ivrFlag)) {
            sql.WHERE("ivr_flag = '" + ivrFlag + "'");
        }

        if(customerType != null){
            sql.WHERE("customer_type = " + customerType);
        }

        if(businessType != null){
            sql.WHERE("business_type = " + businessType);
        }

        if(endTimestamp != null){
            sql.WHERE("version_timestamp <= '" + endTimestamp + "'");
        }

        System.out.println("生成SQL:" + sql.toString() + "  ORDER BY version_timestamp DESC limit " + count);
        return sql.toString() + "  ORDER BY version_timestamp DESC limit " + count;
    }


    /**
     * 可以避免SQL注入
     * 动态SQL的构建函数(method)只是构建SQL,值绑定并不是发生在这个阶段。但是在这个阶段显式绑定也没有太大问题。例如 sql.SET("name = #{name}") 写成 sql.SET("name = " + employee.getName()) 也没有什么不可以,除了可能引发SQL注入。
     * @param param
     * @return
     */
    public String queryRecentTop(Map<String, Object> param) {

        SQL sql = new SQL().SELECT("*").FROM(TABLE_NAME);
        if (StringUtils.hasText((String) param.get("ivrFlag"))) {
            sql.WHERE("ivr_flag = #{ivrFlag}");
        }

        if(param.get("customerType") != null){
            sql.WHERE("customer_type = #{customerType}");
        }

        if(param.get("businessType") != null){
            sql.WHERE("business_type = #{businessType}");
        }

        if(param.get("endTimestamp") != null){
            sql.WHERE("version_timestamp <= #{endTimestamp}");
        }

        /*
        SELECT *
                FROM ivr_node_tree
        WHERE (ivr_flag = #{ivrFlag} AND customer_type = #{customerType} AND business_type = #{businessType} AND version_timestamp <= #{endTimestamp})  ORDER BY version_timestamp DESC limit 3
         */
        System.out.println("生成SQL:" + sql.toString() + "  ORDER BY version_timestamp DESC limit " + (Integer)param.get("count"));
        return sql.toString() + "  ORDER BY version_timestamp DESC limit " + (Integer)param.get("count");
    }
}

参考:

[MyBatis spring howto] https://zzyongx.github.io/blogs/mybatis-spring-howto.html




猜你喜欢

转载自blog.csdn.net/daydayupzzc/article/details/80896346