对比介绍:
MyBatis的基本使用:
接口式编程:
创建一个接口,利用SqlSession的getMapper(Class<T> var1)方法使接口和映射文件绑定。
mybatis会为接口创建一个代理实现类执行sql ,命名空间=接口的全类名 sql标签id=方法名
接口类:EmployeeDao 实体类:Employee
EmployeeDao employeeDao = sqlSession.getMapper(EmployeeDao.class); Employee employee = employeeDao.selectById(1); 映射文件: <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace="com.example.dao.EmployeeDao"> <resultMap id="BaseResultMap" type="com.example.pojo.Employee" > <id column="ID" property="id" jdbcType="INTEGER"/> <result column="LAST_NAME" property="lastName" jdbcType="VARCHAR" /> <result column="GENDER" property="gender" jdbcType="VARCHAR" /> <result column="EMAIL" property="email" jdbcType="VARCHAR" /> </resultMap> <select id="selectById" resultMap="BaseResultMap" parameterType="map" > select * from employee where ID = #{id, jdbcType=INTEGER} </select> </mapper>
#{}与${}的区别:
#{}表示是以预编译的形式,将参数设置到sql中,PreStatement,可以防止sql注入;
${}是将取出的值直接拼装在sql中会有安全问题;
大部分情况下都应该使用#{},${}适用于jdbc不支持占位符的地方,比如分表时使用 select * from ${tableName} where ....
MyBatis插件:
利用动态代理的方式在方法级进行拦截,支持拦截的方法:
如果配置了多个拦截器,会通过责任链模式形成一个代理链条,即代理对象代理了另一个代理对象,要注意:
原文:https://www.cnblogs.com/dream2true/p/12528505.html