關本文是Mybatis基礎系列的第四篇文章,點擊下面連接能夠查看前面的文章:html
mybatis基礎系列(二)——基礎語法、別名、輸入映射、輸出映射mysql
mybatis基礎系列(一)——mybatis入門spring
表設計時一般須要分析表與表的關聯關係、數據庫級別表與表之間的業務關係。sql
員工表和部門表之間的關係分析:一個員工只能屬於一個部門。數據庫
需求:查詢出員工編號爲7369的員工信息和部門信息。apache
sql語句:編程
select * from t_emp JOIN t_dept on(t_emp.deptno=t_dept.deptno) where t_emp.empno=7369
看看mybatis中的寫法緩存
mapper.xmlspringboot
<select id="queryEmpDeptInfo" parameterType="com.itpsc.request.EmpRequest" resultType="com.itpsc.vo.EmpVo"> select * from t_emp JOIN t_dept on(t_emp.deptno=t_dept.deptno) where t_emp.empno=#{emp.empno} </select>
擴展Emp類增長部門熟悉
public class EmpVo extends Emp{ //增長dept表的屬性 private Integer deptno; private String dname; private String loc; //.... }
運行結果
==> Preparing: select * from t_emp JOIN t_dept on(t_emp.deptno=t_dept.deptno) where t_emp.empno=? ==> Parameters: 7369(Integer) <== Columns: empno, ename, job, mgr, hiredate, sal, comm, deptno, deptno, dname, loc <== Row: 7369, SMITH, CLERK, 7902, 1980-12-17, 800.00, null, 20, 20, RESEARCH, DALLAS <== Total: 1 Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@266e9dda] Emp{empno=7369, ename='SMITH', job='CLERK', mgr=7902, hiredate=Wed Dec 17 00:00:00 CST 1980, sal=800.0, comm=null, deptno=null}
從上面能夠看出,若是輸出映射的實體類中沒有包括查詢出來的列名,須要增長列名對應的屬性,便可完成映射。
除了用EmpVo類繼承Emp類而且增長部門屬性外,也能夠在Emp類中增長Dept類型的對象來完成映射。mapper.xml中association 標籤來映射關聯對象。
public class Emp { private Integer empno; private String ename; private String job; private Integer mgr; private Date hiredate; private Float sal; private Float comm; private Integer deptno; private Dept dept; //.... }
mybatis的寫法
<select id="queryEmpDeptInfo" parameterType="com.itpsc.request.EmpRequest" resultMap="empMap"> select * from t_emp JOIN t_dept on(t_emp.deptno=t_dept.deptno) where t_emp.empno=#{emp.empno} </select> <resultMap id="empMap" type="com.itpsc.entity.Emp" > <result column="empno" property="empno" jdbcType="INTEGER" /> <result column="ename" property="ename" jdbcType="VARCHAR" /> <result column="job" property="job" jdbcType="VARCHAR" /> <result column="mgr" property="mgr" jdbcType="INTEGER" /> <result column="hiredate" property="hiredate" jdbcType="DATE" /> <result column="sal" property="sal" jdbcType="REAL" /> <result column="comm" property="comm" jdbcType="REAL" /> <result column="deptno" property="deptno" jdbcType="INTEGER" /> <association property="dept" javaType="com.itpsc.entity.Dept"> <result column="deptno" property="deptno" jdbcType="INTEGER" /> <result column="dname" property="dname" jdbcType="VARCHAR" /> <result column="loc" property="loc" jdbcType="VARCHAR" /> </association> </resultMap>
運行結果
==> Preparing: select * from t_emp JOIN t_dept on(t_emp.deptno=t_dept.deptno) where t_emp.empno=? ==> Parameters: 7369(Integer) <== Columns: empno, ename, job, mgr, hiredate, sal, comm, deptno, deptno, dname, loc <== Row: 7369, SMITH, CLERK, 7902, 1980-12-17, 800.00, null, 20, 20, RESEARCH, DALLAS <== Total: 1 Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@2a87ba34] Emp{empno=7369, ename='SMITH', job='CLERK', mgr=7902, hiredate=Wed Dec 17 00:00:00 CST 1980, sal=800.0, comm=null, deptno=20, dept=Dept{deptno=20, dname='RESEARCH', loc='DALLAS'}}
部門表和員工表之間的關係分析:一個部門能夠有多個員工。
需求:查詢部門編號爲20的全部員工的信息。
sql語句語法:
select t_emp.* from t_emp JOIN t_dept on(t_emp.deptno=t_dept.deptno) where t_dept.deptno=20;
看看mybatis中的寫法:
<select id="queryEmpInfoByDeptno" parameterType="com.itpsc.request.EmpRequest" resultType="com.itpsc.entity.Emp"> select t_emp.* from t_emp JOIN t_dept on(t_emp.deptno=t_dept.deptno) where t_dept.deptno=#{emp.deptno}; </select>
運行結果
==> Preparing: select t_emp.* from t_emp JOIN t_dept on(t_emp.deptno=t_dept.deptno) where t_dept.deptno=?; ==> Parameters: 20(Integer) <== Columns: empno, ename, job, mgr, hiredate, sal, comm, deptno <== Row: 7369, SMITH, CLERK, 7902, 1980-12-17, 800.00, null, 20 <== Row: 7566, JONES, MANAGER, 7839, 1981-04-02, 2975.00, null, 20 <== Row: 7788, SCOTT, ANALYST, 7566, 1987-04-19, 3000.00, null, 20 <== Row: 7876, ADAMS, CLERK, 7788, 1987-05-23, 1100.00, null, 20 <== Row: 7902, FORD, ANALYST, 7566, 1981-12-03, 3000.00, null, 20 <== Row: 7100, itpsc, mannager, 7902, 1980-01-10, null, 1000.00, 20 <== Row: 7101, itpsc2, developer, 7902, 1980-01-10, 2000.00, 1000.00, 20 <== Total: 7
部門表和員工表之間的關係分析:一個部門能夠有多個員工。
員工表和技能表之間的關係分析:一個員工能夠有多個技能。
需求:查詢部門編號爲20的全部員工的信息,並查詢這些員工擁有的技能。
Sql 語句:
select t1.*,t_skill.* from ( select t_dept.*, t_emp.empno, t_emp.ename, t_emp.job, t_emp.mgr, t_emp.hiredate, t_emp.sal from t_emp JOIN t_dept on(t_emp.deptno=t_dept.deptno) where t_dept.deptno=20) t1 join t_skill on (t1.empno=t_skill.empno);
DeptMapper.xml
<mapper namespace="com.itpsc.mapper.DeptMapper" > <!--查詢部門信息--> <resultMap id="deptMap" type="com.itpsc.entity.Dept" > <result column="deptno" property="deptno" jdbcType="INTEGER" /> <result column="dname" property="dname" jdbcType="VARCHAR" /> <result column="loc" property="loc" jdbcType="VARCHAR" /> <!--查詢部門下的員工信息,一個部門有多個員工,用collection--> <collection property="empList" ofType="com.itpsc.entity.Emp"> <result column="empno" property="empno" jdbcType="INTEGER" /> <result column="ename" property="ename" jdbcType="VARCHAR" /> <result column="job" property="job" jdbcType="VARCHAR" /> <result column="mgr" property="mgr" jdbcType="INTEGER" /> <result column="hiredate" property="hiredate" jdbcType="DATE" /> <result column="sal" property="sal" jdbcType="REAL" /> <result column="comm" property="comm" jdbcType="REAL" /> <collection property="skillList" ofType="com.itpsc.entity.Skill"> <result column="skillid" property="skillid" jdbcType="INTEGER" /> <result column="empno" property="empno" jdbcType="INTEGER" /> <result column="sname" property="sname" jdbcType="VARCHAR" /> <result column="descs" property="descs" jdbcType="VARCHAR" /> </collection> </collection> </resultMap> <select id="queryByDeptno" parameterType="com.itpsc.request.EmpRequest" resultMap="deptMap"> select t1.*,t_skill.* from ( select t_dept.*, t_emp.empno, t_emp.ename, t_emp.job, t_emp.mgr, t_emp.hiredate, t_emp.sal from t_emp JOIN t_dept on(t_emp.deptno=t_dept.deptno) where t_dept.deptno=#{emp.deptno}) t1 join t_skill on (t1.empno=t_skill.empno); </select> </mapper>
運行結果
==> Preparing: select t1.*,t_skill.* from ( select t_dept.*, t_emp.empno, t_emp.ename, t_emp.job, t_emp.mgr, t_emp.hiredate, t_emp.sal from t_emp JOIN t_dept on(t_emp.deptno=t_dept.deptno) where t_dept.deptno=?) t1 join t_skill on (t1.empno=t_skill.empno); ==> Parameters: 20(Integer) ... <== Total: 6 Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@1129829c] Dept{deptno=20, dname='RESEARCH', loc='DALLAS', empList=[Emp{empno=7100, ename='itpsc', job='mannager', mgr=7902, hiredate=Thu Jan 10 00:00:00 CST 1980, sal=null, comm=null, deptno=null, skillList=[Skill{skillid=1001, empno=7100, sname='mybatis', descs='database crud'}, Skill{skillid=1002, empno=7100, sname='mysql', descs='data store'}, Skill{skillid=1003, empno=7100, sname='java', descs='program language'}]}, Emp{empno=7369, ename='SMITH', job='CLERK', mgr=7902, hiredate=Wed Dec 17 00:00:00 CST 1980, sal=800.0, comm=null, deptno=null, skillList=[Skill{skillid=1004, empno=7369, sname='spring', descs='spring'}, Skill{skillid=1005, empno=7369, sname='spring mvc', descs='spring mvc'}, Skill{skillid=1006, empno=7369, sname='thymealf', descs='thymealf'}]}]}
resultType:將查詢結果按照表列名與java對象屬性名一一對應映射到java對象中。
resultMap:自定義表列名與java對象屬性名之間的映射關係。結合association和collection完成一對一和一對多高級映射。association標籤的做用是將關聯的信息映射到一個對象中,實現一對一的映射。而collection標籤將關聯信息映射到一個list集合中,實現一對多的映射。
上面咱們已經知道使用association、collection能夠實現一對一及一對多映射,association、collection還有另一個延遲加載的功能。
延遲加載(lazy load)是關聯對象默認的加載方式,延遲加載機制是爲了不一些無謂的性能開銷而提出來的,所謂延遲加載就是當在真正須要數據的時候,才真正執行數據加載操做。
mybatis默認沒有開啓延遲加載功能,須要在springboot的yml配置文件中啓動延遲加載功能:
mybatis-plus:
mapper-locations: "classpath:com/itpsc/mapper/**/*.xml"
type-aliases-package: "com.itpsc.entity"
global-config:
db-column-underline: true
configuration:
map-underscore-to-camel-case: true
cache-enabled: true #配置的緩存的全局開關
lazyLoadingEnabled: true #延時加載的開關
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #打印sql語句,調試用
好比查詢員工信息的時候關聯查詢員工的部門信息。咱們能夠先把員工信息查詢出來,當遍歷員工信息須要查詢對應的部門信息的時候,就能夠調用員工的getDept()方法去加載部門信息。
EmpMapper.xml
<!--resultMap 延遲加載--> <resultMap id="empLazyLoadDeptMap" type="com.itpsc.entity.Emp" > <result column="empno" property="empno" jdbcType="INTEGER" /> <result column="ename" property="ename" jdbcType="VARCHAR" /> <result column="job" property="job" jdbcType="VARCHAR" /> <result column="mgr" property="mgr" jdbcType="INTEGER" /> <result column="hiredate" property="hiredate" jdbcType="DATE" /> <result column="sal" property="sal" jdbcType="REAL" /> <result column="comm" property="comm" jdbcType="REAL" /> <result column="deptno" property="deptno" jdbcType="INTEGER" /> <!--延遲加載關聯對象,Emp對象中延遲加載Dept對象--> <association property="dept" javaType="com.itpsc.entity.Dept" select="com.itpsc.mapper.DeptMapper.queryByDeptno" column="deptno"> </association> </resultMap> <select id="queryEmpLazyLoadDept" resultMap="empLazyLoadDeptMap"> select * from t_emp; </select>
DeptMapper.xml
<select id="queryByDeptno" parameterType="int" resultType="com.itpsc.entity.Dept"> select * from t_dept where t_dept.deptno=#{emp.deptno} </select>
測試代碼
@Test public void testQueryEmpLazyLoadDept() { List<Emp> empList = empService.queryEmpLazyLoadDept(); System.out.println(empList.size()); for(int i=0;i<empList.size();i++) { Emp emp = empList.get(i); System.out.println("員工信息:" + emp.toString()); System.out.println("員工全部部門信息:" + emp.getDept()); } }
運行結果
JDBC Connection [com.mysql.jdbc.JDBC4Connection@1cd6b1bd] will not be managed by Spring ==> Preparing: select * from t_dept where t_dept.deptno=? ==> Parameters: 10(Integer) <== Columns: deptno, dname, loc <== Row: 10, ACCOUNTING, NEW YORK <== Total: 1 員工信息:Emp{empno=7934, ename='MILLER', job='CLERK', mgr=7782, hiredate=Sat Jan 23 00:00:00 CST 1982, sal=1300.0, comm=null, deptno=10, skillList=null} 員工全部部門信息:Dept{deptno=10, dname='ACCOUNTING', loc='NEW YORK'}
從運行結果能夠看出,調用Emp對象的getDept()方法是,才發出查詢部門信息的sql語句,達到延遲加載的做用。
緩存的做用,主要是爲了提升查詢訪問速度,某些數據被頻繁查詢時,能夠緩存到內存中而不是每次都從數據庫查詢,這樣能夠減輕數據庫壓力。
MyBatis的緩存機制,根據緩存的做用域(生命週期)能夠劃分爲2種:一級查詢緩存和二級查詢緩存。
一級緩存是SqlSession級別的緩存。每一個SqlSession中持有了Executor,每一個Executor中有一個HashMap類型的Cache(咱們稱爲Local cache)。不一樣的SqlSession之間的緩存數據區域(HashMap)是互相不影響的。其做用域是SqlSession,當一個SqlSessoin結束後,該SqlSession中的一級查詢緩存也就不存在了。
當用戶發起查詢時,在Local Cache進行查詢,若是緩存命中的話,直接返回結果給用戶,若是緩存沒有命中的話,查詢數據庫結果寫入Local Cache,最後返回結果給用戶。
@Test public void testQueryById() { System.out.println(empService.queryById(7369)); System.out.println(empService.queryById(7369)); }
運行結果
Creating a new SqlSession SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@66d25ba9] was not registered for synchronization because synchronization is not active JDBC Connection [com.mysql.jdbc.JDBC4Connection@31efacad] will not be managed by Spring ==> Preparing: SELECT * FROM t_emp WHERE empno=? ==> Parameters: 7369(Integer) <== Columns: empno, ename, job, mgr, hiredate, sal, comm, deptno <== Row: 7369, SMITH, CLERK, 7902, 1980-12-17, 800.00, null, 20 <== Total: 1 Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@66d25ba9] Emp{empno=7369, ename='SMITH', job='CLERK', mgr=7902, hiredate=Wed Dec 17 00:00:00 CST 1980, sal=800.0, comm=null, deptno=20, skillList=null} Creating a new SqlSession SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@2df65a56] was not registered for synchronization because synchronization is not active JDBC Connection [com.mysql.jdbc.JDBC4Connection@31efacad] will not be managed by Spring ==> Preparing: SELECT * FROM t_emp WHERE empno=? ==> Parameters: 7369(Integer) <== Columns: empno, ename, job, mgr, hiredate, sal, comm, deptno <== Row: 7369, SMITH, CLERK, 7902, 1980-12-17, 800.00, null, 20 <== Total: 1 Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@2df65a56] Emp{empno=7369, ename='SMITH', job='CLERK', mgr=7902, hiredate=Wed Dec 17 00:00:00 CST 1980, sal=800.0, comm=null, deptno=20, skillList=null}
從上面的結果能夠看出,執行2次queryById方法分別建立了2次SqlSession,也就是mybatis的一級緩存沒有起做用,這是由於與spring框架整合後的致使的。
mybatis的會話提供了編程式的事務管理,經過SqlSession.commit(), SqlSession.rollback() or SqlSession.close()這些方法進行事務管理。可是當與spring整合後,事務將交由spring管理,這就意味着你不能手動編程式的管理事務了。spring對mybatis的sqlsession的使用是由template控制的,每次數據庫操做申請一個sqlsession,使用完後就關閉。因此就產生了上面一級緩存失效的問題。
mybaits的二級緩存是mapper範圍級別,多個SqlSession之間能夠共享二級緩存。二級緩存開啓後,每個namespace的mapper都有一個二緩存區域。當開啓二級緩存後,數據的查詢執行的流程就是二級緩存 -> 一級緩存 -> 數據庫。
開啓二級緩存,實體要實現Serializable接口序列化。
mybatis-plus:
mapper-locations: "classpath:com/itpsc/mapper/**/*.xml"
type-aliases-package: "com.itpsc.entity"
global-config:
db-column-underline: true
configuration:
map-underscore-to-camel-case: true
cache-enabled: true #打開二級緩存
lazyLoadingEnabled: true #延時加載的開關
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #打印sql語句,調試用
測試代碼
@Test public void testQueryById() { System.out.println(empService.queryById(7369)); System.out.println(empService.queryById(7369)); }
運行結果
Creating a new SqlSession SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@7db40fd5] was not registered for synchronization because synchronization is not active Cache Hit Ratio [com.itpsc.mapper.EmpMapper]: 0.0 JDBC Connection [com.mysql.jdbc.JDBC4Connection@670342a2] will not be managed by Spring ==> Preparing: SELECT * FROM t_emp WHERE empno=? ==> Parameters: 7369(Integer) <== Columns: empno, ename, job, mgr, hiredate, sal, comm, deptno <== Row: 7369, SMITH, CLERK, 7902, 1980-12-17, 800.00, null, 20 <== Total: 1 Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@7db40fd5] Emp{empno=7369, ename='SMITH', job='CLERK', mgr=7902, hiredate=Wed Dec 17 00:00:00 CST 1980, sal=800.0, comm=null, deptno=20, skillList=null} Creating a new SqlSession SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@c412556] was not registered for synchronization because synchronization is not active Cache Hit Ratio [com.itpsc.mapper.EmpMapper]: 0.5 Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@c412556] Emp{empno=7369, ename='SMITH', job='CLERK', mgr=7902, hiredate=Wed Dec 17 00:00:00 CST 1980, sal=800.0, comm=null, deptno=20, skillList=null}
能夠看出,建立了兩個SqlSession,第二次會話並無去數據庫查詢而是從二級緩存中查詢。
在statement中設置useCache=」false」能夠禁用當前select語句的二級緩存,默認狀況是true。以下:
<select id="queryById" parameterType="int" resultType="com.itpsc.entity.Emp" useCache="false"> SELECT * FROM t_emp WHERE empno=#{empno} </select>
一般狀況下insert、update、delete操做後須要刷新緩存,這時能夠在對應的statement中設置flushCache="true",默認狀況下爲true。
<insert id="add" parameterType="com.itpsc.entity.Emp" flushCache="true"> insert into t_emp(empno,ename,job,mgr,hiredate,sal,comm,deptno) values(#{empno},#{ename},#{job},#{mgr},#{hiredate,jdbcType=DATE},#{sal},#{comm},#{deptno}) </insert>