mybatis學習筆記一

[TOC]

框架技術

框架技術.png

持久化

持久化1.png
持久化2.jpg

mybatis概念

  • 概念:一個持久層框架

  • 作用:ORM將sql語句映射成實體類

  • 特點:巧靈活、半自動化、使用與中小型項目的開發

mybatis 入門

1.png

1、創建mybatis-config.xml文件

<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
        <property name="driver" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/bank?useUnicode=true&characterEncoding=utf-8"/>
        <property name="username" value="root"/>
        <property name="password" value=""/>
      </dataSource>
    </environment>
  </environments>
  <mappers>
    <mapper resource="UserMapper.xml"/>
  </mappers>
</configuration>

2、創建映射文件

<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

  <mapper namespace="user">
    <select id="selectUser" resultType="com.hemi.mybatis.bean.User">
        select * from user where uid=1;
    </select>
  </mapper>

3、獲取xml配置文件

InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");

4、創建SqlSessionFactory

SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(inputStream);

5、獲取SqlSession

SqlSession sqlSession = factory.openSession();

6、調用SqlSession的selectOne(命名空間.id名稱);

Object object = sqlSession.selectOne("user.selectUser");

7、關閉SqlSession

sqlSession.close();

增刪改

2.png
<insert id="insertUser" parameterType="com.hemi.mybatis.bean.User">
    <!-- 通過#{屬性名}來獲取對象的值 -->
    insert into user (username,password) values(#{username},#{password}); 
</insert>

<update id="updateUser" parameterType="com.hemi.mybatis.bean.User">
    update user set username=#{username},password=#{password} where uid=#{uid}
</update>

3.png
<delete id="deleteUser" parameterType="int">
    delete from user where uid=#{value}
</delete>

Mapper接口開發

一、定義一個接口

public interface TypeMapper {
    Type selectType(int typeid);
}

二、定義一個mapper.xml映射文件

mapper文件的要求:

1、namespace的值就是對象接口的全類名,并且類名和xml文件名保持一致
2、id的值就是抽象方法
3、resultType的值必須和抽象方法的返回值一致
4、parameterType的值和抽象方法的參數類型一致

注意 mapper.xml文件的約束是mapper.dtd,不是config.dtd

三、使用

將mybatis入門步驟中的步驟六改為如下代碼:

TypeMapper mapper=sqlSession.getMapper(TypeMapper.class);
Type type=mapper.selectType(1);

動態sql

if

  SELECT * FROM good INNER JOIN type ON good.type = type.typeid where 1=1
    <if test="gname !=null and gname !=''">
      and gname like concat('%',#{gname},'%')
    </if>

注意:

1、字符串的拼接建議使用concat來代替${}

2、判斷條件中獲取數據不用加#{},與el表達式不一樣

where

作用where可以自動去除第一個and

 <where>
      <if test="gname !=null and gname !=''">
        and gname like concat('%',#{gname},'%')
      </if>
      <if test="typename !=null and typename!=''">
        and typename like concat('%',#{typename},'%')
      </if>
    </where>

choose when otherwise

作用:組合使用,相當于if else if else

<select id="findActiveBlogLike"
     resultType="Blog">
  SELECT * FROM BLOG WHERE state = 'ACTIVE'
  <choose>
    <when test="title != null">
      AND title like #{title}
    </when>
    <when test="author != null and author.name != null">
      AND author_name like #{author.name}
    </when>
    <otherwise>
      AND featured = 1
    </otherwise>
  </choose>
</select>

set

  update good 
     <set>
        <if test="gname!=null and gname!=''">
          gname=#{gname},
        </if>
        <if test="gprice!=null and gprice!=''">
          gprice=#{gprice}
        </if>
      </set>
  where gid=#{gid}

trim

作用:去除多余字符串

兩種常見的用法

1、where and

prefix:字首 prefixOverrides:去除第一個指定的字符串

    select * from good
    <trim prefix="where" prefixOverrides="and|or">
      <!--添加where在前面,并且去除第一個and-->
      <if test="gname !=null and gname !=''">
        and gname like concat('%',#{gname},'%')
      </if>
      <if test="typename !=null and typename!=''">
        and typename like concat('%',#{typename},'%')
      </if>
    </trim>

2、set

prefix:字首 suffixOverrides:去除最后指定的字符串

    update good 
    <trim prefix="set" suffixOverrides=",">
      <!--添加set在前面,并且去除最后一個,-->
        <if test="gname!=null and gname!=''">
          gname=#{gname},
        </if>
        <if test="gprice!=null and gprice!=''">
          gprice=#{gprice},
        </if>
      </trim>

foreach

作用:動態循環拼接sql部分內容

1、open代表在集合前面添加的字符串

2、close代表在集合后面添加的字符串

3、separator代表集合分割使用的字符串

4、collection代表被循環的集合,值可以是list、map、array

5、常見用法,in的語句

<select id="selectGoodByGid" parameterType="list" resultType="Good">
    select gid,gname,gprice,count,type typeid from good
    <where>
      gid in

      <foreach item="item" collection="list" open="(" separator="," close=")">
             #{item}
        </foreach>
    </where>
  </select>

1、如何配置多個數據庫
使用environment可以配置多個數據庫,通過ID來表示
2、transactionManager的type有哪些
JDBC、MANAGED

3、dataSource作用
配置數據源,有三種類型:UNPOOLED、POOLED、JNDI還可以配置四大參數(驅動。url/用戶名、密碼)

4、properties有什么用,如何用
加載配置文件(resource/url),
配置鍵值對(proprerty)
注意:如果resource和proprerty,resource優先級高

5、typeAliases有什么用,如何用
起別名
用類名(類名)

6、databaseIdProvider + databaseid

7、databaseIdProvider:給數據庫起別名

8、databaseid:在statement中使用
myBatista根據url可以自動使用當前是什么數據庫,然后使用哪個sql語句

9、mapper中的namespace有什么用
如果有相同的statementid的時候,使用namespace類區別
使用mapper接口開發dao時,namespace與接口全類名一致

10、增刪改查
id:statement的唯一標識,或者說是調用方法名
parameterType:傳入參數的數據類型 基本數據(可以不寫)+引用類型(必須寫)
resultType:返回數據類型
parameterType和resultType:都可以使用別名來表示數據類名

11、myBatista中的數據類型的別名
Integer Integer,int
int _int

12、#{}作用
獲取傳入數據

13、Mapper接口開發的四大要求
1、namespace的值就是對象接口的全類名,并且類名和xml文件名保持一致
2、id的值就是抽象方法
3、resultType的值必須和抽象方法的返回值一致
4、parameterType的值和抽象方法的參數類型一致

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • MyBatis是什么 MyBatis的前身就是iBatis,iBatis本是apache的一個開源項目,2010年...
    吳旭光閱讀 642評論 0 0
  • 參考書籍 原著:Java Persistence with MyBatis 3. 作者:K.Siva Prasad...
    LOOK_LOOK閱讀 548評論 0 0
  • 1. Java基礎部分 基礎部分的順序:基本語法,類相關的語法,內部類的語法,繼承相關的語法,異常的語法,線程的語...
    子非魚_t_閱讀 31,767評論 18 399
  • 1. 簡介 1.1 什么是 MyBatis ? MyBatis 是支持定制化 SQL、存儲過程以及高級映射的優秀的...
    笨鳥慢飛閱讀 5,657評論 0 4
  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,973評論 19 139