穷且益坚,不坠青云之志

1.动态 sql 生成

  1. foreach 循环

delete from 表 where id in(1008,1011,1012);

<!-- list (1008,1011,1012, 1013) -->
<delete id="" parameterType="list">
delete  from 表 where id in  
</delete>
  1. if where 生成动态sql
<where> 能够生成 where 关键字,并去除多余的 and
<if test="条件"> sql 片段 </if>
  1. 对于大于小于条件的处理
    方法1: 对每个特殊字符转转义,例如 < <
    方法2: <![CDATA[ 内容 ]]>

  2. #{ } 与 ${ } 的区别

  • #{ } 底层是替换为 ?, 只能占位值
  • ${ } 底层是直接拼接字符串, 有注入攻击问题
  • 尽量使用 #{ } , 只有在某些功能不能用 #{ } 实现时(例如排序)采用 ${ }

2. Mapper 接口

@Insert @Option
@Update
@Delete
@Select

原理

// 这个类是使用了 jdk的动态代理技术 在代码运行期间生成的类 
public class $Proxy10 implements StudentMapper{
    private SqlSession sqlSession;
    public $Proxy10(SqlSession sqlSession) {
        this.sqlSession = sqlSession;
    }
    // 其中 sql语句从@Insert注解获得, 参数对象就是student
    public void insert(Student student) {
        sqlSession.insert(sql, 参数对象)
    }

    // 其中 sql语句从@Select注解获得
    public List<Student> findAll() {
        return sqlSession.selectList(sql);
    }
}

3. Mapper接口不足

1. 接口方法不能直接应用多个方法参数

解决方法:

  1. 用map传递多个参数, 每个参数对应map中的一个键值对
  2. 用@Param注解

2. Mapper 接口中不能有方法的重载

定义方法是不要方法名冲突
异常信息:

### Cause: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: java.lang.IllegalArgumentException: Mapped Statements collection already contains value for 接口名.方法名(重复的)

3. 使用Mapper接口方式实现动态sql比较复杂

方法1: 结合Mapper接口和xml文件