------------------------------------MyBatis---------------------------------
一、mybatis介绍
1、为什么要使用mybatis(jdbc的缺点)?
手动创建和释放连接
对结果的解析
sql语言硬编码在代码中
2、什么是mybatis?
mybatis前身是apache的ibatis,是一个封装了jdbc的持久层框架,使开发者只需关注sql即可
二、mybatis入门
1、pom.xml
mybatis、mysql-connector-java、log4j、junit
2、log4j.properties
参考2.2
3、pojo
参考2.3
4、mybatis-config.xml
<configuration>
<!--使用dev环境-->
<environments default="dev">
<!--dev环境-->
<environment id="dev">
<transactionManager type="JDBC"></transactionManager>
<!--使用连接池中的数据源-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis?characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="1111"/>
</dataSource>
</environment>
</environments>
<!-- 扫描映射文件 -->
<mappers>
<mapper resource="com/by/dao/UserDao.xml"/>
</mappers>
</configuration>
5、mapper
public interface UserDao{
List<User> findAll();
}
6、mapper.xml
<mapper namespace="com.by.dao.UserDao">
<select id="findAll" resultType="com.by.pojo.User">
select * from user
</select>
</mapper>
7、pom.xml
<build>
<!-- 如果不添加此节点src/main/java目录下的所有配置文件都会被漏掉。 -->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
三、mybatis的运行原理
mybatis-config.xml
mapper.xml mapper.xml mapper.xml
|
|
Resource
|
|--->inputStream
|
SqlSessionFactoryBuilder
|
|--->Configuration(conn, Map<namespace+id, MappedStatement(sql, resultType)>)
|
SqlSessionFactory
|
|--->Configuration(conn, Map<namespace+id, MappedStatement(sql, resultType)>)
|
SqlSession(创建mapper接口的代理类)
|
|--->Map<namespace+id, MappedStatement(sql, resultType)>, conn
|
ProxyFactory
|
|--->MappedStatement, conn
|
Executor
| |
| |
| |
输入参数映射 输出结果映射
四、mybatis传递多个参数
1、按序号传参【不推荐】
WHERE id=#{arg0} AND username=#{arg1}
WHERE id=#{param1} AND username=#{param1}
2、注解传参【推荐】
User getUser2(@Param("id") Integer id, @Param("username") String username);.
SELECT * FROM user WHERE id=#{id} AND username=#{username}
3、对象传参【推荐】
User getUser3(User user);
select * from user where id=#{id} and username=#{username}
4、map传参【不推荐】
User getUser4(Map map)
select * from user where id=#{id} and username=#{username}
五、#{}和${}区别
底层 jdbc类型转换 sql注入 单个简单类型参数
#{} preparedStatement 转换 防止 任意
${} Statement 不转换 不防止 value
注意:除模糊查询外,尽量不适用${}
六、mybatis的主键回填
方式一:
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
SELECT LAST_INSERT_ID()
</selectKey>
方式二:
<insert id="" useGeneratedKeys="true" keyProperty="id" parameterType="">
七、mybatis的orm映射
1、字段起别名
SELECT id, role_name as roleName, role_desc as roleDesc FROM role
2、ResultMap结果映射
<ResultMap id="findAllResult" type="com.by.pojo.Role">
<id column="" property="">
<result column="" property="">
</ResultMap>
<select id="findAll" resultMap="findAllResult">
八、mybatis的别名
1、mybatis默认支持的别名
统统小写 统统基本类型 集合统统用接口
2、自定义别名
<typeAliases>
<package name="com.by.pojo"/>
</typeAliases>
九、批量引入mapper映射文件
<mappers>
<package name="com.by.mapper"/>
</mappers>
十、mybatis的关联查询
1、一对一
<resultMap id="" type="">
....
<association property="user" javaType="com.by.pojo.User">
....
</association>
</resultMap>
2、一对多
<resultMap id="" type="">
....
<collection property="user" ofType="com.by.pojo.Account">
....
</collection>
</resultMap>
3、多对多
<resultMap id="" type="">
....
<collection property="user" ofType="com.by.pojo.Role">
....
</collection>
</resultMap>
十一、延迟加载
1、延迟加载
<resultMap id="getUserById2Result" type="com.by.pojo.User">
... ...
<!--
property="accountList":pojo的属性
ofType="account":集合的泛型
select="com.by.mapper.AccountMapper.selectAccountByUid":要调用的select标签的id
column="id":传递的参数
fetchType="lazy":局部开启延迟加载
-->
<collection property="accountList"
ofType="account"
select="com.by.mapper.AccountMapper.selectAccountByUid"
column="id"
fetchType="lazy">
</collection>
</resultMap>
<select id="getUserById2" parameterType="int" resultMap="getUserById2Result">
select * from user where id=#{id}
</select>
2、全局开启延迟加载
<settings>
<setting name="lazyLoadingEnabled" value="true"/>
</settings>
十二、mybatis的动态sql
1、if标签
<if test="username!=null and username!=''">
AND username=#{username}
</if>
2、where标签
<!--where标签将if标签代码块包起来,并去掉开头 “AND” 或 “OR”-->
<where>
<if test="id != null">
AND id=#{id}
</if>
</where>
3、set标签
<!--set标签将if标签代码块包起来,并去掉最后一个“,”-->
<set>
<if test="username!=null and username != '' ">
username=#{username},
</if>
</set>
4、trim标签
INSERT INTO user
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="username!=null and username!=''">
username,
</if>
</trim>
<trim prefix="VALUES (" suffix=")" suffixOverrides=",">
<if test="username!=null and username!=''">
#{username},
</if>
</trim>
5、foreach标签
void deleteUserByIds(@Param("idArr") Integer[] idArr);
<!--
collection:取值list、array、@Param("keyName")
item="id":循环每次取出的具体对象
open="(" :加上前缀
close=")" :加上后缀
separator=",":分隔符
-->
<foreach collection="idArr" item="id" open="(" close=")" separator=",">
#{id}
</foreach>
6、sql标签
<sql id="get_user_where">
<if test="username!=null and username != ''">
and username=#{username}
</if>
<if test="birthday!=null">
and birthday=#{birthday}
</if>
<if test="sex!=null and sex != ''">
and sex=#{sex}
</if>
<if test="address!=null and address != ''">
and address=#{address}
</if>
</sql>
<where>
<!--refid="get_user_where":sql标签的id-->
<include refid="get_user_where"></include>
</where>
十三、mybatis的缓存
1、一级缓存
范围:一级缓存范围是sqlSession
配置:默认开启
走缓存:同一个sqlsession执行同一条sql
不走缓存:不同sqlSession 或 两次查询之间执行了增删改
2、二级缓存
范围:二级缓存范围是sqlSessionFactory
配置:<cache></cache>
走缓存:同一个sqlSessionFactrory,sqlsession执行commit或close
不走缓存:不同sqlSessionFactrory 或 两次查询之间执行了增删改