MyBatis的作用
MyBatis是持久层的框架,封装了几乎所有的JDBC代码,使用简单的XML或注解配置和定义映射关系。
MyBatis的体系结构
- 加载配置
一种是XML配置文件,一种是Java代码的注解。将SQL的配置信息加载成一个个的MappedStatement对象 - SQL解析
- SQL执行
- 结果映射 (可以转换成HasjMap,javaBean或基本数据类型)
MyBatis的配置文件
- SqlMapConfig.xml(1个)
主配置文件,用于指定数据库链接参数和框架参数 - SqlMap.xml(n个)
映射定义文件,用于定义SQL语句和映射信息
SqlMapConfig.xml:
<configuration>
<environments default="environment">
<environment id="environment">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver"
value="oracle.jdbc.OracleDriver" />
<property name="url"
value="jdbc:oracle:thin:@192.168.0.23:1521:tarena10g"/>
<property name="username" value="demo" />
<property name="password" value="demo" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="目录路径/SqlMap.xml" />
</mappers>
</configuration>
SqlMap.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"
"http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">
<mapper namespace="org.tarena.mapper.EmpMapper">
<cache/>
<!-- 按名字查询 -->
<select id="findLikeName" resultType="Emp" parameterType="Emp" >
select * from EMP where 1=1
<choose>
<when test="ename != null">
and ENAME like #{ename}
</when>
<otherwise>
and ENAME like '%A%'
</otherwise>
</choose>
</select>
<!-- in条件 -->
<select id="findByDeptNos" resultType="Emp" parameterType="Emp" >
select * from EMP
<if test="deptnos != null">
where DEPTNO in
<foreach collection="deptnos"
item="dno" open="(" close=")" separator=",">
#{dno}
</foreach>
</if>
</select>
<!-- where -->
<select id="findByCondition" resultType="Emp" parameterType="Emp" >
select * from EMP
<where>
<if test="deptno != null">
DEPTNO = #{deptno}
</if>
<choose>
<when test="ename != null">
and ENAME like #{ename}
</when>
<otherwise>
and ENAME like '%A%'
</otherwise>
</choose>
</where>
</select>
<!-- 批量插入 -->
<insert id="add" parameterType="Emp">
insert into EMP (EMPNO,ENAME,SAL,COMM,DEPTNO)
values (#{empno},#{ename},#{sal},#{comm},#{deptno})
</insert>
<!-- 返回Map -->
<select id="findEmps" resultType="java.util.HashMap">
select EMPNO from EMP
</select>
</mapper>
MyBatis实例
- SqlSessionFactoryBuilder
该对象根据MyBatis配置文件SqlMapConfig.xml构建SqlSessionFactory实例 - SqlSessionFactory
创建SqlSession实例 - SqlSession
该对象包含了所有执行Sql操作的方法,用于执行已经映射的SQL语句