一、Mybatis的框架介紹
- 核心組態檔
- properties屬性
- typeAliases型別別名的設定
- environments 環境配置
- 添加映射檔案
- plugings分頁插件的使用
- 類的映射檔案
- namespace命名空間
- 增刪改查的sql標簽
- ResultMap的使用
- 資料添加后回傳主鍵selectKey
- sql片段
- Mybatis的動態sql
- if where標簽
- choose標簽
- set標簽
- trim標簽
- foreach標簽
- Mybatis的延遲加載
- mybatis的快取機制
- 一級快取
- 二級快取
- Mybatis的核心API介紹
- Resources
- SqlSessionFactoryBuilder
- SqlSessionFactroy
- SqlSession
- 基于介面代理方式實作開發
- Mybatis的多表聯合查詢
- 關聯查詢
- 多對一查詢
- 一對多查詢
- 多對多查詢
- 嵌套查詢
- 多對一查詢
- 一對多
- 多對多
- Mybatis的注解
- 常用的注解
- Mybatis是一個持久層的框架、也是一個半自動的ORM(object relational mapping)框架
核心組態檔
properties屬性
可以創建一個properties檔案,將驅動、url、用戶名和密碼存放在其中
db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql:///資料庫的名稱
db.username=用戶名
db.password=密碼
好處:我們切換資料的時候只需要更改properties檔案中的配置即可
核心組態檔參考properties的方法
<properties resource="db.properties">
typeAliases型別別名的設定
當我們正常使用映射檔案的時候,要求resultType必須要寫全名稱,若我們在核心組態檔中設定別名,就可以簡寫
<!--當映射檔案中出現person就表示是com.jiale.beans.Person的物件-->
<typeAliases>
<typeAlias type="com.jiale.beans.Person" alias="Person">
</typeAliases>
注意:別名可以忽略大小寫
若專案中的別名有很多,需要配置很多的別名,可以通過package的方式來配置
<!--表示當前包下的所有物體類都配置了別名,別名的名稱是類名-->
<typeAliases>
<package name="com.jiale.beans">
</typeAliases>
environments 環境配置
配置資料庫中的連接環境
<!--在配置的多個環境中,默認使用哪一個-->
<environments default="development">
<!--單個環境的唯一標識,和default中的必須寫一樣的-->
<environment id="development">
<!--事務管理,當前的連接是否使用事務-->
<transactionManager type="JDBC"/>
<!--dateSource資料源 連接資料庫的基礎設定-->
<dateSource type="POOLED">
<property name="driver" value="${db.driver}"/>
<property name="url" value="${db.url}"/>
<property name="username" value="${db.username}"/>
<property name="password" value="${db.password}"/>
</dateSource>
</environment>
</environments>
- transcationManager配置事務管理,目前可以配置兩個引數
JDBC:使用jdbc的事務管理,也意味著開啟了事務
MANAGED:不使用事務,mybatis不使用事務,適合mybatis和其他框架、插件配合使用,其他框架來做事務管理 - dateSource 資料源屬性 type屬性
POOLED:直接使用jdbc的連接池,但是使用連接池的概念,插件連接后,將連接放入到容器中來使用
UNPOOLED:不使用連接池的概念,每次訪問都是新建一個連接
JNDI:使用第三方的連接池 c3p0 dbcp
添加映射檔案
<mappers>
<mapper resource="PersnMapper.xml">
</mappers>
plugings分頁插件的使用
1.添加依賴
2.核心組態檔中添加設定
<!--配置第三方的插件-->
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
</plugins>
3.正常查詢的時候添加分頁設定
//添加分頁設定
PageHelper.startPage(2,4);//當前的頁數為2,每頁的條數為4
4.可以使用分頁提供的工具類
pageNum:當前的頁數 pageSize:每頁的條數 size:當前頁的條數 prePage:上一頁的頁碼
nextPage:下一頁的頁碼 isFirstPage:是不是第一頁 isLastPage:是不是最后一頁 total:資料的總條數
類的映射檔案
namespace命名空間
<mapper namespace="">
增刪改查的sql標簽
<insert id="addPerson" parameterType="com.jiale.beans.Person">
insert into person (name,sex,age) values(#{name},#{sex},#{age})
</insert>
<select id="getPerById" parameterType="int" resultType="com.jiale.beans.Person">
select * from person where id=#{id}
</select >
每個增刪改查都有一個id,作為當前sql陳述句的唯一標識
parameterType:表示當前sql傳入的引數,如果傳入的引數是物件,必須要寫全名稱
resultType:只能在select標簽中使用,表示查詢后回傳的結果去映射的那個物件,如果回傳的是多個資料,mybatis會自動封裝為list集合,我們需要配置的是list集合的泛型型別
ResultMap的使用
使用前提:創建的物件和資料庫表不能自動映射(物件的屬性和資料庫中的名稱不一樣),可以通過手動的方法來實作
<!--自定義映射結果集 id的唯一標識 type 將結果映射到那個類中-->
<resultMapid="baseUser" type="User">
<!--配置標簽有兩個id和result,效果是一樣的-->
<!--每個標簽中都可以設定property物件的屬性和column資料庫的列-->
<id property="id" column="id"/>
<result property="name" column="uname"/>
<result property="age" column="uage"/>
</resultMap>
<!--使用resultMap,必須是使用手動映射-->
<select id="getPerById" parameterType="int" resultType="baseUser">
select * from person where id=#{id}
</select >
資料添加后回傳主鍵selectKey
<insert id="addPerson" parameterType="com.jiale.beans.Person">
<!--在添加陳述句后執行對應的查詢,將查詢的結果賦值到id中-->
<selectKey order="AFTER" keyProperty="id" resultType="int">
SELECT LAST_INSERT_ID()
</selectKey >
insert into person (name,sex,age) values(#{name},#{sex},#{age})
</insert>
sql片段
類似于java中的封裝,將重復出現的sql陳述句封裝到sql片段中,在標簽內進行呼叫
<!--添加一個sql片段將重復的SQL進行封裝-->
<sql id="selectColumn">
select id,name,sex,age from person
</sql>
<!--呼叫-->
<include refid="selectColumn">
Mybatis的動態sql
if where標簽
if:if條件如果成立,sql就執行,如果使用多個使用and和or連接
where:判斷where標簽內是否有sql陳述句,有就添加,沒有就不添加,可去掉sql最前面的and或or
select * from person
<where>
<if test="name != null and name != ''">
and name like concat("%",concat(#{name},"%"))
</if>
<if test="sex!= null and sex!= ''">
and sex = #{sex}
</if>
<if test="hobby != null and hobby != ''">
and hobby= #{hobby}
</if>
</where>
choose標簽
一套判斷,該判斷里面只有一個判斷是正確的
select * from person
<choose>
<when test="name != null and name != ''">
where name like concat("%",concat(#{name},"%"))
</when>
<when test="sex!= null and sex!= ''">
where sex = #{sex}
</when>
<when test="hobby != null and hobby != ''">
where hobby= #{hobby}
</when>
<otherwise>
where age = 28
</otherwise>
</choose>
set標簽
自動在標簽的sql陳述句前面添加set,自動去掉后面的
update person
<set>
<if test="name != null and name != ''">
and name like concat("%",concat(#{name},"%"))
</if>
<if test="sex!= null and sex!= ''">
and sex = #{sex}
</if>
<if test="hobby != null and hobby != ''">
and hobby= #{hobby}
</if>
</set>
<where>
<if test="id != null and id != ''">
and id= #{id}
</if>
</where>
使用set標簽的優點:避免了傳遞物件沒有屬性,在資料庫中將對應的引數修改為null的情況
trim標簽
去掉SQL陳述句的前后空格,還有個特殊的屬性
prefix:添加前綴 suffix:添加后綴 prefixOverrides:去掉前綴 suffixOverrides:去掉后綴
select * from person
<trim prefix="where" prefixOverrides="and">
<where>
<if test="name != null and name != ''">
and name like concat("%",concat(#{name},"%"))
</if>
<if test="sex!= null and sex!= ''">
and sex = #{sex}
</if>
<if test="hobby != null and hobby != ''">
and hobby= #{hobby}
</if>
</where>
foreach標簽
遍歷標簽,如果傳遞的資料是個陣列或者集合,才會使用遍歷標簽
標簽的屬性:
collection:需要遍歷的集合 item:表示迭代后每個物件的名稱 open:在遍歷開始前sql陳述句前面添加的內容
close:在遍歷開始后sql陳述句前面添加的內容 separator:在遍歷的程序中每次遍歷中間添加的內容
insert into person (name,sex,age)
<foreach collection="list" item="per" open="values(" close=")" separator="),(">
#{per.name},#{per.sex},#{per.age}
</foreach>
Mybatis的延遲加載
1.延遲加載的概述
只能在嵌套回圈里面使用,延遲加載也叫懶加載、按需加載
在資料使用的情況下去加載資料,不使用就不加載,mybatis默認是關閉的,在正常使用中,如果加載的資料是大量的資料,加載的時候就會發生延遲,降低用戶的使用體驗,延遲加載根據具體的使用情況來決定是否使用
2.延遲加載的實作
(1)匯入依賴cglib
(2)區域延遲加載:fetchType=“lazy”
區域延遲加載的配置:必須在所有的association和collection標簽中添加fetchType,如果不添加就沒有延遲加載,會將所有的資料都查詢
(3)全域延遲加載
在核心組態檔中設定
<settings>
<!--開啟全域的延遲加載-->
<setting name="lazyLodingEnabled" value="true"/>
<!--將讀取任意屬性就加載所有資料關閉-->
<setting name="aggressiveLazyLoading" value="false"/>
</settings>
全域延遲加載的配置簡單,但是不能精確的定義延遲加載具體的使用
mybatis的快取機制
查詢的時候,同一個查詢執行多次,浪費資料庫的資源,在mybatis中可以使用查詢快取,查詢的結果放入記憶體中,下一次查詢直接獲取
如果要使用快取,需要將物件做序列化的操作
一級快取
sqlsession級別的快取,默認是開啟的
快取的資料什么時候清理
1.關閉sqlsession的時候
2.執行對應的刪改陳述句
二級快取
sqlsessionFactory級別的快取,sqlsessionFactory在專案運行的時候創建,在專案關閉的時候銷毀,二級快取是默認關閉的,二級快取是分塊的,根據命名空間區分的,
開啟二級快取,物體類必須序列化們沒有序列化會報例外
implements Serializeable
在核心組態檔的settings里面設定
<!--開啟二級快取-->
<setting name="cacheEnabled" value="true">
在映射檔案中配置
<!--開啟當前映射檔案的二級快取-->
<cache/>
二級快取是一般專案優化最常用的一種
Mybatis的核心API介紹
Resources
作用:讀取一個檔案將檔案轉化為位元組流檔案
//讀取核心組態檔,轉化為一個流物件
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactoryBuilder
作用:將讀取到的流物件創建一個sqlsession工廠
//創建一個sqlsession工廠
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
SqlSessionFactroy
作用:生產sqlsession物件
//生產sqlsession物件
SqlSession sqlSession = factory.openSession();
SqlSession
作用:可以呼叫五個方法來操作資料庫insert update delete selectOne selectList
int i = sqlSession.insert("namespace.方法",p);
在執行增刪改方法的時候使用commit方法,提交事務
還可以呼叫一個close方法 關閉sqlsesion
基于介面代理方式實作開發
優點:呼叫方法的入參都是由自己定義的,回傳值型別包括是否增刪改查的方法都是自己判斷的
1.介面的開發規則
在映射檔案中,namespace必須是介面的全名稱
介面中的方法名必須和映射檔案中標簽的id一致
介面中的方法對應的入參必須和映射檔案中標簽中的parameterType一致
介面中的方法對應的回傳值必須要和映射檔案標簽中的resultType型別一樣(如果回傳的是集合,映射檔案配置的是泛型的型別,介面要配置list
2.配置calss實作介面的開發
介面必須和映射檔案的名字一樣
介面必須和映射檔案在同一個目錄下,在resouces中創建和介面同名的檔案夾來存放,
<mappers>
<!--通過calss來配置-->
<mapper calss="con.jiale.mapper.Test"/>
</mappers>
<mappers>
<!--表示該包下的所有介面都配置了calss-->
<package name="con.jiale.mapper"/>
</mappers>
Mybatis的多表聯合查詢
關聯查詢
一次性將所有表的資料都查詢出來
多對一查詢
在dog類中添加一個person 表示多對一的關系
映射檔案的配置
<mapper namespace="com,jiale.mapper.DogMapper">
<!--自定義結果集 需要將person的資料進行匹配-->
<resultMap id="baseDog" type="Dog">
<id property="did" column="did"/>
<result property="dname" column="dname"/>
<result property="color" column="color"/>
<!--專門設定多對一的標簽 association-->
<association property="per" javaType="Person">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="sex" column="sex"/>
<result property="age" column="age"/>
</association>
</resultMap>
一對多查詢
在person中添加一個List集合,表示所有的dog
映射檔案的配置
<mapper namespace="com,jiale.mapper.DogMapper">
<!--自定義結果集 需要將person的資料進行匹配-->
<resultMap id="basePerson" type="Person">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="sex" column="sex"/>
<result property="age" column="age"/>
<!--專門設定一對多的標簽 collection ofType:集合泛型的型別-->
<collection property="dogs" javaType="Dog">
<id property="did" column="did"/>
<result property="dname" column="dname"/>
<result property="color" column="color"/>
</collection>
</resultMap>
多對多查詢
創建學生類有List集合,表示一個學生對應多個中間表的課程
創建課程類有LIst集合,表示每個課程對應多個中間表的學生
創建中間表有學生和課程
映射檔案的配置
<!--自定義結果集 學生型別-->
<resultMap id="baseStudent" type="Student">
<id property="sid" column="sid"/>
<result property="sname" column="sname"/>
<result property="ssex" column="ssex"/>
<result property="sage" column="sage"/>
<!--配置學生和中間表的一對多關系-->
<collection property="sc" javaType="Dog">
<id property="scid" column="scid"/>
<result property="score" column="score"/>
</collection>
<!--配置中間表和課程之間的關系-->
<association property="co" javaType="Course">
<id property="cid" column="cid"/>
<result property="cname" column="cname"/>
<result property="ctime" column="ctime"/>
</association>
</resultMap>
嵌套查詢
多對一查詢
根據顏色查詢Dog,并根據id查詢Person
<!--自定義結果集-->
<resultMap id="baseDog" type="Dog">
<id property="did" column="did"/>
<!--設定多對一的關聯關系 column:將第一次查詢結果的某個列的值放入第二次查詢中-->
<!--select:查詢person表要找的方法-->
<association property="per" javaType="Person" column="pid" select="findPerById">
</resultMap>
<!--根據顏色查詢Dog-->
<select id="findDogByColor" parameterType="String" resultMap="baseDog">
select * from dog where color = #{color}
</select >
<!--根據pid查詢person-->
<select id="findPerById" parameterType="int" resultType="Person">
select * from person where id= #{pid}
</select >
一對多
根據id查詢person,再根據pid查詢對應的dog
<!--自定義結果集-->
<resultMap id="basePerson" type="Person">
<!--設定一對多的關聯關系-->
<collection property="dogs" javaType="Dog" column="id" select="findDogByPid">
</resultMap>
<!--根據id查詢person-->
<select id="findPerById" parameterType="int" resultMap="basePerson">
select * from person where id= #{pid}
</select >
<!--根據pid查詢dog-->
<select id="findDogById" parameterType="int" resultType="Dog">
select * from dog where pid= #{id}
</select >
多對多
查詢大于某個課時時間的課程
<!--自定義課程結果集-->
<resultMap id="baseCourse" type="Course">
<id property="cid" column="cid">
<!--設定一對多的關聯關系-->
<collection property="sc" javaType="SC" column="cid" select="findDogByPid">
</resultMap>
<!--根據課時查詢課程-->
<select id="findCourseByTime" parameterType="int" resultMap="baseCourse">
select * from course where ctime > #{time}
</select >
<!--自定義課程結果集-->
<resultMap id="baseSC" type="SC">
<!--設定多對一的關聯關系-->
<association property="st" javaType="Student" column="sid" select="findStudentBySid">
</resultMap>
<!--根據課程的cid查詢中間表的方法-->
<select id="findSCByCid" parameterType="int" resultMap="baseSC">
select * from student_course where cid= #{cid}
</select >
<!--根據sid查詢學生的方法-->
<select id="findStudentBySid" parameterType="int" resultType="Student">
select * from student where sid= #{sid}
</select >
Mybatis的注解
常用的注解
@insert @delete @update @select :curd
@results:和resultMap一樣,自定義結果集 @result:在results下面使用,做列和屬性的映射
@one :配置多對一映射 @many:配置一對多映射
@Insert("insert into person (name,sex,age) values (#{name},#{sex},#{age})")
//多對一
@Select("select * from dog where did = #{did}")
@Results({
@Result(property = "did",column="did"),
@Result(property = "person",javaType="Person.calss"column="pid"),
one = @One(select = "findPerById")
})
Dog findDogByDid(Integer did);
//一對多
@Select("select * from person where id= #{id}")
@Results({
@Result(property = "id",column="id"),
@Result(property = "dogs",javaType="List.calss"column="id"),
many= @Many(select = "findDogByPid")
})
Dog findPerById(Integer id);
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/267106.html
標籤:其他
下一篇:Mysql資料庫知識總結
