MyBatis學習筆記

MyBatis

ORMapping:Object Relationship Mapping 對象關係映射java

對象指面向對象mysql

關係指關係型數據庫sql

Java到MySQL的映射,開發者能夠以面向對象的思想來管理數據庫數據庫

如何使用

  • 新建Maven工程,pom.xml
<dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>
        
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.11</version>
        </dependency>
        
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.6</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
    
    <build>
    
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
        
    </build>
  • 新建數據表
use mybatis;
create table t_account(
id int primary key auto_increment,
username varchar(11),
password varchar(11),
age int 
)
  • 新建數據表對應的實體類Account
package com.janeroad.entity;
import lombok.Data;

[@Data](https://my.oschina.net/difrik)
public class Account {
    private long id;
    private String username;
    private String password;
    private int age;
}
  • 建立MyBatis的配置文件config.xml,文件名可自定義
<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 
        "http://mybatis.org/dtd/mybatis-3-config.dtd"> 
<configuration>   
    <!--配置MyBatis運行環境 -->   
    <environments default="development">     
        <environment id="development">     
            <!-- 配置JDBC事務管理 -->          
            <transactionManager type="JDBC"></transactionManager>   
            <!-- POOLED配置JDBC數據源鏈接池 -->          
            <dataSource type="POOLED">             
                <property name="driver" value="com.mysql.cj.jdbc.Driver"> 
                </property>               
                <property name="url" 
                          value="jdbc:mysql://localhost:3306/mybatis? 
                          useUnicode=true&amp;characterEncoding=UTF-8">
                    
                </property>             
                <property name="username" value="root"></property>      
                <property name="password" value="root"></property>     
            </dataSource>    
        </environment>   
    </environments> 
</configuration>

使用原生接口apache

一、MyBatis框架須要開發者自定義SQL語句,寫在Mapper.xml文件中,實際開發中,會爲每一個實體類建立對應的Mapper.xml,定義管理該對象數據的SQLapi

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.janeroad.mapper.AccoutMapper">
    <insert id="save" parameterType="com.janeroad.entity.Account">
      insert into t_account(username,password,age) values(#{username},# {password},#{age})
     </insert>

</mapper>
  • namespace一般設置爲文件所在包+文件名的形式緩存

  • insert標籤表示執行添加操做session

  • select標籤表示執行查詢操做mybatis

  • update標籤表示執行更新操做app

  • delete標籤表示執行刪除操做

  • id是實際調用MyBatis方法時須要用到的參數

  • parameterType是調用對應方法時參數的數據類型

二、全局配置文件config.xml中加入 註冊AccountMapper.xml

<!--註冊AccountMapper.xml -->
    <mappers>
        <mapper resource="com/southwind/mapper/AccountMapper.xml"></mapper>
    </mappers>

三、調用MyBatis的原生接口執行添加操做

public class Test {
     public static void main(String[] args) {
         //加在MyBatis配置文件
         InputStream inputStream = Test.class.getClassLoader().getResourceAsStream("config.xml");
         SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
         SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
         SqlSession sqlSession = sqlSessionFactory.openSession();
         String statement = "com.janeroad.mapper.AccoutMapper.save";
         Account account = new Account(1L,"張三","123123",22);
         sqlSession.insert(statement,account);
         sqlSession.commit();
     }
}

經過Mapper代理實現自定義接口

  • 自定義接口,定義相關業務方法
  • 編寫與方法相對應的Mapper.xml

一、自定義接口

package com.janeroad.repository;

import com.janeroad.entity.Account;

import java.util.List;

public interface AccountRepository {
    public int save(Account account);
    public int update(Account account);
    public int deleteById(long id);
    public List<Account> findAll();
    public Account findById(long id);
    public Account findByName(String name);
    public Account findById2(Long id);
    public Account findByNameAndAge(String name,int age);
    public int count();
    public Integer count2();
    public String findNameByID(long id);
}

二、建立接口對應的Mapper.xml,定義接口方法對應的SQL語句

statement標籤可根據SQL執行的業務選擇insert、delete、update、select

MyBatis框架會根據規則自動建立接口實現類的代理對象

規則:

  • Mapper.xml中namespace爲接口的全類名
  • Mapper.xml中statement的id爲接口中對應的方法名
  • Mapper.xml中statement的parameterType和接口中對應方法的參數類型一致
  • Mapper.xml中statement的和接口中對應方法的返回值類型一致
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.janeroad.repository.AccountRepository">
    <insert id="save" parameterType="com.janeroad.entity.Account">
        insert into t_account(username,password,age) values(#{username},# {password},#{age})
    </insert>
    <update id="update" parameterType="com.janeroad.entity.Account">
    update t_account set username = #{username},password = #{password},
    age = #{age} where id = #{id}
    </update>
    <delete id="deleteById" parameterType="long">
        delete from t_account where id = #{id}
    </delete>
    <select id="findAll" resultType="com.janeroad.entity.Account">
    select * from t_account
    </select>
    <select id="findById" parameterType="long" resultType="com.janeroad.entity.Account">
    select * from t_account where id = #{id}
    </select>
</mapper>

三、在config.xml中註冊AccountRepository.xml

<!--註冊AccountMapper.xml -->
    <mappers>
        <mapper resource="com/janeroad/mapper/AccountMapper.xml"></mapper>
        <mapper resource="com/janeroad/repository/AccountRepository.xml"></mapper>
    </mappers>

四、調用接口的代理對象完成相關的業務操做

package com.janeroad.test;


import com.janeroad.repository.AccountRepository;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;

public class Test2 {
    public static void main(String[] args) {
        InputStream inputStream = Test.class.getClassLoader().getResourceAsStream("config.xml");
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //獲取實現接口的代理對象
       AccountRepository accountRepository = sqlSession.getMapper(AccountRepository.class);
       //添加對象(增)
//      Account account = new Account(2,"李四","123123",23);
//      accountRepository.save(account)
//      sqlSession.commit();
       //查詢所有對象(查)
// 		List<Account> list = accountRepository.findAll();
//      for (Account account:list){
//      System.out.println(account);
//     }
//     sqlSession.close();
       //經過id查詢對象
//     Account account = accountRepository.findById(4L);
//     System.out.println(account);
//     sqlSession.close();
       //修改對象(改)
//        Account account = accountRepository.findById(4L);
//         account.setUsername("小明");
//          account.setPassword("000");
//           account.setAge(18);
//         int result = accountRepository.update(account);
//     sqlSession.commit();
//    System.out.println(result);
//     sqlSession.close();
        //經過ID刪除對象(刪)
    int result = accountRepository.deleteById(4L);
     System.out.println(result);
     sqlSession.commit();
     sqlSession.close();//關閉資源
    }
}

Mapper.xml

  • statement標籤:select、update、insert分別對應查詢、修改、刪除、添加操做
  • parameterType:參數數據類型

一、基本數據類型,經過id查詢Account

<select id="findById" parameterType="long" resultType="com.janeroad.entity.Account">
	select * from t_account where id = #{id}
</select>

二、String類型,經過name查詢Account

<select id="findByName" parameterType="java.lang.String" resultType="com.janeroad.entity.Account">
	select * from t_account where username = #{username}
</select>

三、包裝類,經過id查詢Account

<select id="findById2" parameterType="java.lang.Long" resultType="com.janeroad.entity.Account">
	select * from t_account where id = #{id}
</select>

四、多個參數,經過name和age查詢Account

<select id="findByNameAndAge" resultType="com.janeroad.entity.Account">
	select * from t_account where username = #{arg0} and age = #{arg1}
</select>

五、Java Bean

<update id="update" parameterType="com.janeroad.entity.Account">
    update t_account set username = #{username},password = #{password},
    age = #{age} where id = #{id}
</update>
  • resultType:結果類型

一、基本數據類型,統計Account總數

<select id="count" resultType="int">
	select count(id) from t_account
</select>

二、包裝類,統計Account總數

<select id="count2" resultType="java.lang.Integer">
	select count(id) from t_account
</select>

三、String類型,經過id查詢Account的name

<select id="findNameByID" resultType="java.lang.String">
	select username from t_account where id = #{id}
</select>

四、Java Bean

<select id="findById" parameterType="long" resultType="com.janeroad.entity.Account">
	select * from t_account where id = #{id}
</select>

級聯查詢

  • 一對多

Student

package com.janeroad.entity;

import lombok.Data;

[@Data](https://my.oschina.net/difrik)
public class Student {
    private long id;
    private String name;
    private Classes classes;
}

Classes

package com.janeroad.entity;

import lombok.Data;

import java.util.List;

[@Data](https://my.oschina.net/difrik)
public class Classes {
    private long id;
    private String name;
    private List<String> students;
}

StudentRepository

package com.janeroad.repository;


import com.janeroad.entity.Student;

public interface StudentRepository {
    public Student findById(long id);
}

StudentRepository.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.janeroad.repository.StudentRepository">

    <resultMap id="studentMap" type="com.janeroad.entity.Student">
        <id column="id" property="id"></id>
        <result column="name" property="name"></result>
        <association property="classes" javaType="com.janeroad.entity.Classes">
             <id column="cid" property="id"></id>
             <result column="cname" property="name"></result>
        </association>
    </resultMap>


<select id="findById" parameterType="long" resultMap="studentMap">
select s.id ,s.name ,c.id as cid,c.name as cname  from student s,classes c where s.id=#{id} and s.cid=c.id
</select>

</mapper>

ClassesRepository

package com.janeroad.repository;

import com.janeroad.entity.Classes;


public interface ClassesRepository {
    public Classes findById(long id);
}

ClassesRepository.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.janeroad.repository.ClassesRepository">

    <resultMap id="classesMap" type="com.janeroad.entity.Classes">
        <id column="cid" property="id"></id>
        <result column="cname" property="name"></result>
        <collection property="students" ofType="com.janeroad.entity.Student">
            <id column="id" property="id"/>
            <result column="name" property="name"/>
        </collection>
    </resultMap>


    <select id="findById" parameterType="long" resultMap="classesMap">
select s.id ,s.name ,c.id as cid,c.name as cname  from student s,classes c where c.id=#{id} and s.cid=c.id
</select>

</mapper>
  • 多對多

Customer

package com.janeroad.entity;

import lombok.Data;

import java.util.List;

[@Data](https://my.oschina.net/difrik)
public class Customer {
    private long id;
    private String name;
    private List<Goods> goods;
}

Goods

package com.janeroad.entity;

import lombok.Data;

import java.util.List;

[@Data](https://my.oschina.net/difrik)
public class Goods {
    private long id;
    private String name;
    private List<Customer> customers;
}

CustomerRepository

package com.janeroad.repository;


import com.janeroad.entity.Customer;

public interface CustomerRepository {
    public Customer findById(long id);
}

CustomerRepository.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.janeroad.repository.CustomerRepository">

    <resultMap id="customerMap" type="com.janeroad.entity.Customer">
        <id column="cid" property="id"></id>
        <result column="cname" property="name"></result>
        <collection property="goods" ofType="com.janeroad.entity.Goods">
            <id column="gid" property="id"/>
            <result column="gname" property="name"/>
        </collection>
    </resultMap>


    <select id="findById" parameterType="long" resultMap="customerMap">
select c.id cid ,c.name cname,g.id gid,g.name gname from customer c,goods g ,customer_goods cg
where c.id=#{id}
</select>

</mapper>

GoodsRepository

package com.janeroad.repository;


import com.janeroad.entity.Goods;

public interface GoodsRepository {
public Goods findById(long id);
}

GoodsRepository.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.janeroad.repository.GoodsRepository">

    <resultMap id="goodsMap" type="com.janeroad.entity.Goods">
        <id column="gid" property="id"></id>
        <result column="gname" property="name"></result>
        <collection property="customers" ofType="com.janeroad.entity.Customer">
            <id column="cid" property="id"/>
            <result column="cname" property="name"/>
        </collection>
    </resultMap>


    <select id="findById" parameterType="long" resultMap="goodsMap">
select c.id cid ,c.name cname,g.id gid,g.name gname from customer c,goods g ,customer_goods cg
where g.id=#{id}
and cg.cid=c.id
and cg.gid=g.id
</select>

</mapper>

逆向工程

MyBatis框架須要:實體類、自定義Mapper接口、Mapper.xml

傳統的開發中上述的三個組件須要開發者手動建立,逆向工程能夠幫助開發者來自動建立三個組件,減輕開發者的工做量,提升工做效率。

如何使用

MyBatis Generator ,簡稱MBG,是一個專門爲MyBatis框架開發者定製的代碼生成器,可自動生成MyBatis框架所需的實體類、Mapper接口、Mapper.xml,支持基本的CRUD操做,可是一些相對複雜的SQL須要開發者本身來完成。

  • 新建Maven工程,pom.xml
<dependencies>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.4.5</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.11</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis.generator</groupId>
        <artifactId>mybatis-generator-core</artifactId>
        <version>1.3.2</version>
    </dependency>
</dependencies>
  • 建立MBG配置文件generatorConfig.xml

一、jdbcConnection配置數據庫鏈接信息

二、javaModelGenerator配置JavaBean的生成策略

三、sqlMapGenerator配置SQL映射文件生成策略

四、JavaClientGenerator配置Mapper接口的生成策略

五、table配置目標數據表(tableName:表名,domainObjectName:JavaBean類名)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <context id="testTables" targetRuntime="MyBatis3">
        <jdbcConnection
        driverClass="com.mysql.cj.jdbc.Driver"
        connectionURL="jdbc:mysql://localhost:3306/mybatis? useUnicode=true&amp;characterEncoding=UTF-8"
        userId="root"
        password="123456"></jdbcConnection>
        <javaModelGenerator targetPackage="com.janeroad.entity"
                            targetProject="./src/main/java"></javaModelGenerator>
        <sqlMapGenerator targetPackage="com.janeroad.repository"
                         targetProject="./src/main/java"></sqlMapGenerator>
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.janeroad.repository" targetProject="./src/main/java"></javaClientGenerator>
        <table tableName="t_user" domainObjectName="User"></table>
    </context>
</generatorConfiguration>
  • 建立Generator執行類
package com.janeroad.test;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.exception.InvalidConfigurationException;
import org.mybatis.generator.exception.XMLParserException;
import org.mybatis.generator.internal.DefaultShellCallback;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> warings = new ArrayList<String>();
        boolean overwrite = true;
        String genCig = "/generatorConfig.xml";
        File configFile = new File(Main.class.getResource(genCig).getFile());
        ConfigurationParser configurationParser = new ConfigurationParser(warings);
        Configuration configuration = null;
        try {
            configuration = configurationParser.parseConfiguration(configFile);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (XMLParserException e) {
            e.printStackTrace();
        }
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        MyBatisGenerator myBatisGenerator = null;
        try {
            myBatisGenerator = new MyBatisGenerator(configuration,callback,warings);
        } catch (InvalidConfigurationException e) {
            e.printStackTrace();
        }
        try {
            myBatisGenerator.generate(null);
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

MyBatis延遲加載

  • 什麼是延遲加載?

延遲加載也叫懶加載、惰性加載,使用延遲加載能夠提升程序的運行效率,針對於數據持久層的操做,在某些特定的狀況下去訪問特定的數據庫,在其餘狀況下能夠不訪問某些表,從必定程度上減小了Java應用與數據庫的交互次數。

查詢學生和班級的時候,學生和班級是兩張不一樣的表,若是當前需求只須要獲取學生的信息,那麼查詢學生單表便可,若是須要經過學生獲取對應的班級信息,則必須查詢兩張表。

不一樣的業務需求,須要查詢不一樣的表,根據具體的業務需求來動態減小數據表查詢的工做就是延遲加載。

  • 在config.xml中開啓延遲加載
<settings>
    <!-- 打印SQL-->
    <setting name="logImpl" value="STDOUT_LOGGING" />
    <!-- 開啓延遲加載-->
    <setting name="lazyLoadingEnabled" value="true"/>
</settings>
  • 將多表關聯查詢拆分紅多個單表查詢

StudentRepository

public Student findByIdLazy(long id);

StudentRepository.xml

<resultMap id="studentMapLazy" type="com.janeroad.entity.Student">
    <id column="id" property="id"></id>
    <result column="name" property="name"></result>
    <association property="classes" javaType="com.janeroad.entity.Classes"
    select="com.janeroad.repository.ClassesRepository.findByIdLazy" column="cid"></association>
</resultMap>

<select id="findByIdLazy" parameterType="long" resultMap="studentMapLazy">
    select * from student where id =#{id}
</select>

ClassesRepository

public Classes findByIdLazy(long id);

ClassesRepository.xml

<select id="findByIdLazy" parameterType="long" resultType="com.janeroad.entity.Classes">
select * from classes where id=#{id}
</select>

MyBatis緩存

  • 什麼是MyBatis緩存

使用緩存能夠減小Java應用與數據庫的交互次數,從而提高程序的運行效率。好比查詢出id=1的對象,第一次查詢出以後會自動將該對象將保存到緩存中,當下一次查詢時,直接從緩存中取出對象便可,無需再次訪問數據庫

  • MyBatis緩存分類

一、一級緩存:Sqlsession級別,默認開啓,而且不能關閉。

操做數據庫時須要建立SqlSession對象,在對象中有一個HashMap用於存儲緩存數據,不一樣的SqlSession之間緩存數據區域是互不影響的。

一級緩存的做用域是SqlSession範圍的,當在同一個SqlSession中執行兩次相同的SQL語句時,第一次執行完畢會將結果保存到緩存中,第二次查詢時直接從緩存中獲取。

須要注意的是,若是SqlSession執行了DML操做(insert、update、delete),MyBatis必須將緩存清空以保證數據的準確性。

二、二級緩存:Mapper級別,默認關閉,能夠開啓。

使用二級緩存時,多個SqlSession使用同一個Mapper的SQL語句操做數據庫,獲得的數據會存在二級緩存區,一樣是使用HashMap進行數據存儲,相比較於一級緩存,二級緩存的範圍更大,多個SqlSession能夠共用二級緩存,二級緩存是跨SqlSession的。

二級緩存是多個SqlSession共享的,其做用域是Mapper的同一個namespace,不一樣的SqlSession兩次執行相同的namespace下的SQL語句,參數也相等,則第一次執行成功以後會將數據保存到二級緩存中,第二次可直接從二級緩存中取出數據

代碼

  • 一級緩存
package com.janeroad.test;


import com.janeroad.entity.Account;
import com.janeroad.repository.AccountRepository;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;

public class Test4 {
    public static void main(String[] args) {
        InputStream inputStream=Test.class.getClassLoader().getResourceAsStream("config.xml");
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder=new SqlSessionFactoryBuilder();
        SqlSessionFactory sqlSessionFactory=sqlSessionFactoryBuilder.build(inputStream);
        SqlSession sqlSession=sqlSessionFactory.openSession();
        AccountRepository accountRepository=sqlSession.getMapper(AccountRepository.class);
        //驗證一級緩存
        Account account=accountRepository.findById(1L);
        System.out.println(account);

        Account account1=accountRepository.findById(1L);
        System.out.println(account1);
        //若是關閉SqlSession則會拋出異常關閉後必須從新建立一個,sql語句就沒法再從緩存中讀取,sql語句會執行兩次
//        sqlSession.close();
//        sqlSession=sqlSessionFactory.openSession();
//        accountRepository=sqlSession.getMapper(AccountRepository.class);
//        Account account1=accountRepository.findById(1L);
//        System.out.println(account1);
    }
}
  • 二級緩存

一、MyBatis自帶的二級緩存

  • config.xml中配置開啓二級緩存
<settings>
    <!-- 打印SQL-->
    <setting name="logImpl" value="STDOUT_LOGGING" />
    <!-- 開啓延遲加載-->
    <setting name="lazyLoadingEnabled" value="true"/>
    <!-- 開啓二級緩存-->
    <setting name="cacheEnabled" value="true"/>
</settings>
  • Mapper.xml中配置二級緩存
<cache></cache>
  • 實體類實現序列化接口
package com.janeroad.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Account implements Serializable {
    private long id;
    private String username;
    private String password;
    private int age;
}

二、ehcache 二級緩存

  • pom.xml添加相關依賴
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-ehcache</artifactId>
    <version>1.0.0</version>
</dependency>

<dependency>
    <groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache-core</artifactId>
    <version>2.4.3</version>
</dependency>
  • 添加ehcache.xml
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
     xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">  
<diskStore/>    
<defaultCache    
        maxElementsInMemory="1000"        
        maxElementsOnDisk="10000000"   
        eternal="false"          
        overflowToDisk="false"     
        timeToIdleSeconds="120"  
        timeToLiveSeconds="120"   
        diskExpiryThreadIntervalSeconds="120"        
        memoryStoreEvictionPolicy="LRU">    
</defaultCache> 
</ehcache>
  • config.xml中配置開啓二級緩存
<settings>
    <!-- 打印SQL-->
    <setting name="logImpl" value="STDOUT_LOGGING" />
    <!-- 開啓延遲加載-->
    <setting name="lazyLoadingEnabled" value="true"/>
    <!-- 開啓二級緩存-->
    <setting name="cacheEnabled" value="true"/>
</settings>
  • Mapper.xml中配置二級緩存
<cache type="org.mybatis.caches.ehcache.EhcacheCache">
    <!--緩存建立以後,最後一次訪問緩存的時間至緩存失效的時間間隔 -->
    <property name="timeToIdleSeconds" value="3600"/>
    <!--緩存自建立時間起至失效的時間間隔 -->
    <property name="timeToLiveSeconds" value="3600"/>
    <!--緩存的回收策略,LRU 表示移除近期使用最少的對象 -->
    <property name="memoryStoreEvictionPolicy" value="LRU"/>
</cache>
  • 實體類不須要實現序列化接口
package com.janeroad.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Account  {
    private long id;
    private String username;
    private String password;
    private int age;
}

MyBatis動態SQL

使用動態SQL可簡化代碼的開發,減小開發者的工做量,程序能夠自動根據業務參數來決定SQL的組成

  • if標籤
<select id="findByAccount" parameterType="com.janeroad.entity.Account" resultType="com.janeroad.entity.Account">
select * from t_account where
    <if test="id!=0">
            id = #{id}
    </if>
    <if test="username!=null">
            and username = #{username}
    </if>
    <if test="password!=null">
            and password = #{password}
    </if>
    <if test="age!=0">
            and age = #{age}
    </if>
</select>

if 標籤能夠自動根據表達式的結果來決定是否將對應的語句添加到SQL中,若是條件不成立則不添加,若是條件成立則添加。

  • where標籤
<select id="findByAccount" parameterType="com.janeroad.entity.Account" resultType="com.janeroad.entity.Account">
select * from t_account
<where>
    <if test="id!=0">
        id = #{id}
    </if>
    <if test="username!=null">
        and username = #{username}
    </if>
    <if test="password!=null">
        and password = #{password}
    </if>
    <if test="age!=0">
        and age = #{age}
    </if>
</where>

</select>

where標籤能夠自動判斷是否要刪除語句塊中的and關鍵字,若是檢測到where直接跟and拼接,則自動刪除and,一般狀況下if和where結合起來使用

  • choose、when標籤
<select id="findByAccount" parameterType="com.janeroad.entity.Account" resultType="com.janeroad.entity.Account">   
	select * from t_account    
	<where>     
		<choose>    
			<when test="id!=0">
				id = #{id}    
			</when>        
			<when test="username!=null">      
				username = #{username}        
			</when>         
			<when test="password!=null">         
				password = #{password}       
			</when>          
			<when test="age!=0">
				age = #{age}       
			</when>     
		</choose>  
	</where>
</select>
  • trim標籤

trim標籤中的prefix和suffix屬性會被用於生成實際的SQL語句,會和標籤內部的語句進行拼接,若是語句先後出現了prefixOverrides或suffixOverrides屬性中指定的值,MyBatis框架會自動將其刪除

<select id="findByAccount" parameterType="com.janeroad.entity.Account" resultType="com.janeroad.entity.Account">   
	select * from t_account  
    <trim prefix="where" prefixOverrides="and">      
    	<if test="id!=0">           
        	id = #{id}        
        </if>        
        <if test="username!=null">        
        	and username = #{username}  
        </if>       
        <if test="password!=null">  
        	and password = #{password}
        </if>      
        <if test="age!=0">    
        	and age = #{age}     
        </if>    
	</trim>
</select>
  • set標籤

set標籤用於update操做,會自動根據參數選擇生成SQL語句(減小沒必要要的SQL賦值)

<update id="update" parameterType="com.janeroad.entity.Account">    
	update t_account    
	<set>        
		<if test="username!=null">         
			username = #{username},
   	    </if>    
    	<if test="password!=null">           
    		password = #{password},     
    	</if>    
    	<if test="age!=0">    
            age = #{age}      
    	</if>    
    </set>  
    where id = #{id} 
</update>
  • foreach標籤

foreach標籤能夠迭代生成一系列值,這個標籤主要用於SQL的in語句

(等於一次調用屢次的findById方法,調出數據,須要先在account實體類裏定義一個Long類型的 ids集合,在經過account.setIds()方法賦值給ids集合 )

<select id="findByIds" parameterType="com.janeroad.entity.Account" resultType="com.janeroad.entity.Account">     
	select * from t_account     
	<where>         
		<foreach collection="ids" open="id in (" close=")" item="id" 
separator=",">         
			#{id}         
		</foreach>   
	</where> 
</select>

PS:四天學完MVC,兩天學完Mybatis,累死了,之後要多複習幾遍!!

相關文章
相關標籤/搜索