Mybatis知识点整理

Mybatis含义及优缺点

Mybatis就是一个实现了数据持久化的开源框架,简单理解就是对JDBC进行封装。

Mybatis的优点
  • 与JDBC相比,减少了50%以上的代码量
  • Mybatis是最简单的持久化框架,小巧并且简单易学
  • Mybatis相当灵活,不会对应用程序或者数据库的现有设计强加任何影响,SQL卸载XML里,从程序代码中彻底分离,降低耦合度,便于统一管理和优化,并可重用
  • 提供XML标签,支持编写动态SQL语句
  • 提供映射标签,支持对象与数据库的ORM字段关系映射
Mybatis的缺点
  • SQL语句的编写工作量较大,尤其是字段多、关联表多时,更是如此,对开发人员编写SQL语句的功底有一定要求。
  • SQL语句依赖于数据库,导致数据库移植性差,不能随意更换数据库。
核心接口和类

SqlSessionFactoryBuilder==>SqlSessionFactory==>SqlSession

如何使用

  • 新建maven工程,pom.xml
<dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>
        
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.20</version>
        </dependency>
        
		<dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.4</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
  • 创建数据表
    在这里插入图片描述
  • 新建数据表对应的实体类
package com.southwind.entity;

import lombok.Data;

@Data
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>

MyBatis的开发方式

  • 使用原生接口
  • Mapper代理实现自定义接口
使用原生接口

1、MyBatis框架需要开发者自定义SQL语句,写在Mapper.xml文件中,实际开发中,会为每个实体类创建对应的Mapper.xml,定义管理该对象数据的SQL。

<?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.southwind.mapper.AccountMapper">

    <insert id="save" parameterType="com.southwind.entity.Account">
        insert into t_account(username, password, age) values(#{username},#{password},#{age})
    </insert>

</mapper>
  • namespace通常设置为文件所在包+文件名的形式
  • insert标签表示执行添加操作
  • select标签表示执行查询操作
  • update标签表示执行更新操作
  • delete标签表示执行删除操作
  • id是实际调用MyBatis方法时需要用到的参数
  • parameterType是调用对应方法时参数的数据类型

2、在全局配置文件config.xml中注册AccountMapper.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>
    <!-- 注册AccountMapper.xml -->
    <mappers>
        <mapper resource="com/southwind/mapper/AccountMapper.xml"></mapper>
    </mappers>

</configuration>

3、调用MyBatis的原生接口执行添加操作

public class Test {
    public static void main(String[] args) {
        //1.加载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.southwind.mapper.AccountMapper.save";
        Account account = new Account(1L, "张三","qweqe", 22);
        sqlSession.insert(statement, account);
        sqlSession.commit();
    }
}
通过Mapper代理实现自定义接口
  • 定义自定义接口,定义相关业务方法
  • 编写与方法相对应的Mapper.xml

1、自定义接口

package com.southwind.repository;

import com.southwind.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);

}

2、创建接口对应的Mapper.xml,定义接口方法对应的SQL语句;
statement标签可以跟SQL执行的业务选择insert、delete、update、select。
MyBatis框架会根据规则自动创建接口实现类的代理对象

规则:

  • Mapper.xml中namespace为接口的全类名
  • Mapper.xml中statement的id为接口中对应的方法名
  • Mapper.xml中statement的parameterType和接口中对应方法的参数类型一致
  • Mapper.xml中statement的resultType和接口中对应方法的返回值类型一致
<?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.southwind.repository.AccountRepository">
    <insert id="save" parameterType="com.southwind.entity.Account">
        insert into t_account(username,password,age) values(#{username},#{password},#{age})
    </insert>

    <update id="update" parameterType="com.southwind.entity.Account">
        update t_account set username = #{username},password=#{password},age=#{age} where id=#{id}
    </update>

    <delete id="deleteById" parameterType="java.lang.Long">
        delete from t_account where id=#{id}
    </delete>
    
    <select id="findAll" resultType="com.southwind.entity.Account">
        select * from t_account
    </select>
    
    <select id="findById" parameterType="long" resultType="com.southwind.entity.Account">
        select * from t_account where id=#{id}
    </select>
</mapper>

3、在config.xml中注册AccountRepository.xml

<mappers>
        <mapper resource="com/southwind/mapper/AccountMapper.xml"></mapper>
        <mapper resource="com/southwind/repository/AccountRepository.xml"></mapper>
</mappers>

4、调用接口的代理对象完成相关的业务操作

package com.southwind.test;

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

import java.io.InputStream;
import java.util.List;

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);
        //查询全部对象
//        List<Account> list = accountRepository.findAll();
//        for(Account account:list){
//            System.out.println(account);
//        }
        //添加对象
//        Account account = new Account(2L, "wangwu","nkbad",23);
//        accountRepository.save(account);
//        sqlSession.commit();
        //通过id查询并修改对象
//        Account account = accountRepository.findById(3);
//        account.setUsername("jajaj");
//        int result = accountRepository.update(account);
//        System.out.println(result);
//        sqlSession.commit();
//        sqlSession.close();
        //通过id删除对象
        int result = accountRepository.deleteById(3);
        System.out.println(result);
        sqlSession.commit();
        sqlSession.close();
    }
}

Mapper.xml

  • statement标签:select、update、delete、insert分别对应查询、修改、删除、添加操作

  • parameterType:表示参数数据类型

    • (基本数据类型,通过id查询Account==>int)
    • (String类型,通过name查询Account)
    • 包装类,通过id查询account(与基本数据类型差不多,java.lang.Long)
    • 多个参数,通过username和age查询account,用param1,param2…
    • Java Bean,update命令中,parameterType=com...Account
  • resultType:结果类型

    • 基本数据类型,统计Account总数
    • 包装类,resultType=“java.lang.Integer”
    • String类型,resultType=“String”
    • Java Bean,resultType=“com...Account”
级联查询

Student

package com.southwind.entity;

import lombok.Data;

@Data
public class Student {
    private long id;
    private String name;
    private Classes classes;
}

Classes

package com.southwind.entity;

import java.util.List;

public class Classes {

    private long id;
    private String name;

    private List<Student> students;
}

StudentRepository

package com.southwind.repository;

import com.southwind.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.southwind.repository.StudentRepository">
    
    <resultMap id="studentMap" type="com.southwind.entity.Student">
        <id column="id" property="id"></id>
        <result column="name" property="name"></result>
        <association property="classes" javaType="com.southwind.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.southwind.repository;

import com.southwind.entity.Classes;

public interface ClassesRepository {

    public Classes findById(long id);
}

ClassesRepository.xml

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

<mapper namespace="com.southwind.repository.ClassesRepository">
    <resultMap id="classesMap" type="com.southwind.entity.Classes">
        <id column="cid" property="id"></id>
        <result column="cname" property="name"></result>
        <collection property="students" ofType="com.southwind.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.southwind.entity;
import lombok.Data;

import java.util.List;

@Data
public class Customer {
    private long id;
    private String name;
    private List<Goods> goods;
}

Goods

package com.southwind.entity;

import lombok.Data;

import java.util.List;

@Data
public class Goods {
    private long id;
    private String name;
    private List<Customer> customers;
}

CustomerRepository

package com.southwind.repository;

import com.southwind.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.southwind.repository.CustomerRepository">
    
    <resultMap id="customerMap" type="com.southwind.entity.Customer">
        <id column="cid" property="id"></id>
        <result column="cname" property="name"></result>
        <collection property="goods" javaType="com.southwind.entity.Goods">
            <id column="gid" property="id"></id>
            <result column="gname" property="name"></result>
        </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,customer_goods cg,goods g where c.id=#{id} and cg.cid=c.id and cg.gid=g.id;
    </select>
</mapper>

GoodsRepository

package com.southwind.repository;

import com.southwind.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.southwind.repository.GoodsRepository">
    
    <resultMap id="goodsMap" type="com.southwind.entity.Goods">
        <id column="gid" property="id"></id>
        <result column="gname" property="name"></result>
        <collection property="customers" javaType="com.southwind.entity.Customer">
            <id column="cid" property="id"></id>
            <result column="cname" property="name"></result>
        </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,customer_goods cg,goods g 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.6</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.20</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.4.0</version>
        </dependency>
    </dependencies>
  • 创建MBG配置文件generatorConfig.xml
    • 1、jdbcConnection配置数据库连接信息
    • 2、javaModelGenerator配置JavaBean的生成策略
    • 3、sqlMapGenerator配置SQL映射文件生成策略
    • 4、javaClientGenerator配置Mapper接口的生成策略
    • 5、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&amp;serverTimezone=GMT%2B8"
                userId="root"
                password="root"
        ></jdbcConnection>
        <javaModelGenerator targetPackage="com.southwind.entity" targetProject="./src/main/java"></javaModelGenerator>
        <sqlMapGenerator targetPackage="com.southwind.repository" targetProject="./src/main/java"></sqlMapGenerator>
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.southwind.repository" targetProject="./src/main/java"></javaClientGenerator>
        <table tableName="t_user" domainObjectName="User"></table>
    </context>
</generatorConfiguration>
  • 创建Generator执行类
package com.southwind.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 throwables) {
            throwables.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

MyBatis延迟加载

  • 什么是延迟加载

延迟加载也叫懒加载、惰性加载,使用延迟加载可以提高程序的运行效率,针对于数据持久层的操作,在某些特定的情况下去访问特定的数据库,在其他的情况下可以不访问某些表,从一定程度上减少了Java应用于数据库的交互次数。

查询学生和班级时,学生和班级是两张不同的表,如果当前需求只需要获取学生的信息,那么查询学生单表即可,如果需要通过学生获取对应的班级信息,则必须查询两张表。

不同的业务需求,需要查询不同的表,根据具体的业务需求来动态减少数据表查询的工作就是延迟加载。

  • 在config.xml中开启延迟加载
<settings>
        <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.southwind.entity.Student">
  <id column="id" property="id"></id>
  <result column="name" property="name"></result>
  <association property="classes" javaType="com.southwind.entity.Classes" select="com.southwind.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.southwind.entity.Classes">
  select * from classes where id = #{id}
</select>

MyBatis缓存

  • 什么是MyBatis缓存

使用缓存可以减少java应用与数据库的交互次数,从而提升程序的执行效率。比如查询id=1的对象,第一次查询出之后会自动将该对象保存到缓存中,当下一次查询时,直接从缓存中取出对象即可,无需再次访问数据库。

  • MyBatis缓存分类

1、一级缓存:SqlSession级别,默认开启,并且不能关闭
操作数据库时需要创建SqlSession对象,在对象中有一个HashMap用于存储缓存数据,不同的SqlSession之间缓存数据区域是互不影响的。

一级缓存的作用域是SqlSession范围的,当在同一个SqlSession中执行两次相同的SQL语句时,第一次执行完毕会将结果保存到缓存中,第二次查询时直接从缓存中获取。

需要注意的是,如果SQLSession执行了DML操作(insert、update、delete),MyBatis必须将缓存清空以保证数据的准确性。

2、二级缓存:Mapper级别,默认关闭,可以开启
使用二级缓存时,多个SqlSession使用同一个Mapper的Sql语句操作数据库,得到的数据会存在二级缓存区,同样使用HashMap进行数据存储,相比较于一级缓存,二级缓存的范围更大,多个SqlSession可以共用,二级缓存是跨SqlSession的。

二级缓存是多个SqlSession共享的,其作用域是Mapper的同一个namespace,不同的SqlSession两次执行相同的namespace下的SQL语句,参数也相等,则第一次执行成功后会将数据保存到二级缓存中,第二次可直接从二级缓存中取出数据。

一级缓存

package com.southwind.test;

import com.southwind.entity.Account;
import com.southwind.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(1);
        System.out.println(account);
        sqlSession.close();
        sqlSession = sqlSessionFactory.openSession();
        accountRepository = sqlSession.getMapper(AccountRepository.class);
        Account account1 = accountRepository.findById(1);
        System.out.println(account1);
    }
}

  • 二级缓存

1、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>
  • 实体类实现序列化接口
@Data
public class Account implements Serializable {
    private int id;
    private String username;
    private String password;
    private int age;
}

2、ehcache二级缓存

  • pom.xml中添加相关依赖
<dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-ehcache</artifactId>
            <version>1.0.0</version>
</dependency>
  • 添加ehcache.xml
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">

    <diskStore path="java.io.tmpdir"/>

    <!--     
    Mandatory Default Cache configuration. These settings will be applied to caches     
    created programmtically using CacheManager.add(String cacheName)     
    -->
    <!--     
       name:缓存名称。     
       maxElementsInMemory:缓存最大个数。     
       eternal:对象是否永久有效,一但设置了,timeout将不起作用。     
       timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。     
       timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。     
       overflowToDisk:当内存中对象数量达到maxElementsInMemory时,Ehcache将会对象写到磁盘中。     
       diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。     
       maxElementsOnDisk:硬盘最大缓存个数。     
       diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.     
       diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。     
       memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。     
       clearOnFlush:内存数量最大时是否清除。     
    -->
    <defaultCache
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            overflowToDisk="true"
            maxElementsOnDisk="10000000"
            diskPersistent="false"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU"
    />
</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>
  • 实体类不需要实现序列化接口

MyBatis动态SQL

使用动态SQL可简化代码的开发,减少开发者的工作量,程序可以自动根据业务参数来决定SQL的组成。

  • if标签
select * from t_account where
<if test="id!=0">
  id=#{id}
</if>
  • where标签

  • choose when标签

  • trim标签

trim标签中的prefix和suffix属性会被用于生成实际的SQL语句,会和标签内部语句进行拼接,如果语句前后出现了prefixOverrides或者suffixOverrides属性中指定的值,MyBatis框架会自动将其删除。

  • set标签
  • foreach标签
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值