天天看點

JavaORM架構之Mybatis篇(Ibatis)

歡迎檢視Java開發之上帝之眼系列教程,如果您正在為Java後端龐大的體系所困擾,如果您正在為各種繁出不窮的技術和各種架構所迷茫,那麼本系列文章将帶您窺探Java龐大的體系。本系列教程希望您能站在上帝的角度去觀察(了解)Java體系。使Java的各種後端技術在你心中子產品化;讓你在工作中能将Java各個技術了然于心;能夠即插即用。本章我們來一起了解ORM(對象關系映射關系)架構之Mybatis(Ibatis)。

主流ORM架構有Mybatis和Hibernate,本章我們将對Mybatis的核心要點進行了解。

什麼是ORM(對象映射關系)架構?

JavaORM架構之Mybatis篇(Ibatis)

 ORM(Object Relational Mapping)對象關系映射,是 一種為了解決面向對象與關系型資料庫不比對而出現的技術,使開發者能夠用面向對象的方式使用關系型資料庫。

Mybatis和Hibernate有什麼異同?

  1. Mybatis簡單,Hibernate較複雜,門檻高。
  2. Mybatis自定制Sql,比Hibernate靈活,可控
  3. Mybatis與資料庫映射得到的PO與Hibernate映射PO意義不同

Mybatis入門起步   Mybatis入門起步完整示例下載下傳

/**
 * @Author:jimisun
 * @Description:
 * @Date:Created in 08:37 2018-09-24
 * @Modified By:
 */
public class Main {
    
    public static void main(String[] args) throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        TestUserMapper mapper = sqlSession.getMapper(TestUserMapper.class);
        TestUser testUser = mapper.selectOne(1);
        System.out.println(testUser.toString());
    }
}      

PS:Mybatis支援注解開發,但需要保留白的XML檔案,也就是保留白的命名空間 ; 如下所示

@Select(" SELECT * from user where id = #{id};")
    MyDto selectOne(Integer id);      
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.jimisun.dao.TestUserMapper">
   <!--空-->
</mapper>      

Mybatis和Spring的內建 Myabtis和Spring整合完整示例代碼下載下傳

如果你使用Mybatis那麼一定會使用Spring,最常見的架構組合就是SSM(SpringMvc+Spring+Mybatis),那麼Mybatis針對和Spring的整合提供了一個類庫(jar包)

<dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.2.2</version>
        </dependency>      

以前我們配置在mybatis裡面的配置,現在我們可以将這些配置轉移到了Spring配置中;統一交給Spring進行管理, Mybatis的配置檔案留白,但是不能删除喲

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <!-- 加載配置檔案 -->
    <context:property-placeholder location="classpath:db.properties"/>

    <!-- 資料庫連接配接池 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
          destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="maxActive" value="10"/>
    </bean>

    <!-- mapper配置 -->
    <!-- 讓spring管理sqlsessionfactory 使用mybatis和spring整合包中的 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 資料庫連接配接池 -->
        <property name="dataSource" ref="dataSource"/>
        <!-- 加載mybatis的全局配置檔案 -->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!-- 掃描entity包 使用别名 -->
        <property name="typeAliasesPackage" value="com.jimisun.domain"/>
        <!-- 掃描sql配置檔案:mapper需要的xml檔案 -->
        <property name="mapperLocations" value="classpath:mapper/*.xml" />
    </bean>

    <!-- 配置掃描Dao接口包,動态實作Dao接口,注入到spring容器中 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 注入sqlSessionFactory -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!-- 給出需要掃描Dao接口包 -->
        <property name="basePackage" value="com.jimisun.dao"/>
    </bean>

</beans>      

Spring和Myabtis整合的有兩個關注點

  1. Myabtis将SqlSessionFactory傳遞Spring管理
  2. Spring将XML對應的接口進行接手管理

Mybatis結果映射 Myabtis自定義結果映射完整示例代碼下載下傳

在實際項目中我們通過使用mybatis查詢資料庫經常使用多表查詢,關聯查詢,或者實體的屬性名和資料庫列名不符等情況...是以查詢的結果存在不定性,我們可以自定義Dto類,在mapper.xml檔案中自定義<resultMap>标簽即可。

<resultMap id="MyDto" type="com.jimisun.domain.dto.MyDto">
        <result property="myid" column="id"></result>
        <result property="myusername" column="username"></result>
    </resultMap>      

Mybatis二級緩存 Mybatis的二級緩存測試示例代碼

雖然很多時候我們在開發中并不經常Mybatis的二級緩存 , 但是如果針對個别SQL進行優化設定能夠極大提升通路資料庫效率 . mybatis支援一級緩存和二級緩存,預設開啟一級緩存,一級緩存使SqlSession級别的,Session結束緩存就清空了,二級緩存使Mapper級别的,需要我們手動開啟。

<!--開啟二級緩存-->
     <cache/>      

針對不需要使用二級緩存的方法設定useCache=false

<select id="selectOne" parameterType="java.lang.Integer" resultType="com.jimisun.domain.TestUser" useCache="false">
      SELECT * from user where id = #{id}
   </select>      

我們進行簡單的測試 , 觀察Mybatis二級緩存是否開啟

public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
        TestUserMapper testUserMapper = (TestUserMapper) context.getBean("testUserMapper");
        /*測試緩存:先查詢此時username為jimisun*/
        TestUser testUser = testUserMapper.selectOne(1);
        /*測試緩存:修改username為lisi*/
        Integer integer = testUserMapper.updateOne(1);
        /*測試緩存:最後查詢檢視是否從資料庫擷取還是從緩存擷取*/
        TestUser resultUser = testUserMapper.selectOne(1);
        System.out.println(resultUser.toString());
    }      

Mybatis其他使用技巧

  • 在mapper.xml編寫sql時對于重複的sql我們可以使用<include refid="id">引用代碼
  • 對于Mybatis非空判斷我們建議這樣使用 <if test="param !=null and param != ''">
  • 一個Mapper.xml中可以直接引用另一個Mapper.xml的resultMap , 不需要重複定義

 Java開發之上帝之眼系列教程其他文章

  • Java開發之上帝之眼系列教程前言和章節目錄彙總
    • JavaMVC架構之SpringMVC
    • JavaIOC架構之Spring Framework

勘誤&感謝

  本系列文章資料來源很多出自于網際網路和在下本身的見解,受限于個人技術能力水準和其他相關知識的限制,相關見解錯誤或者資料引用錯誤請各位幫助留言校正!引用資料多來自于網際網路,在下在引用前會遵循各位前輩或者部落客的引用說明表示感謝,但網際網路資料多是轉發再轉發或存在遺漏請原作者内信聯系指正。

雜家不如專家,精益求精

繼續閱讀