MyBatis學習1--基礎
阿新 • • 發佈:2019-01-24
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語句