快速上手MyBatis

快速上手MyBatis

@Time:2022/1/10

@Record:CodePianist
废话:大概上学期一开学学习Mybatis,经过近五个月的时间,发现知识点遗忘较严重,近日西安疫情后管控在家,重新复习整理一下ssm的内容吧。

MyBatis概括

ORMapping: Object Relationship Mapping 对象关系映射

对象指⾯向对象

关系指关系型数据库

Java 到 MysqL 的映射,开发者可以使用⾯向对象的思想来管理数据库

如何构建

1.新建 Maven ⼯程,pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.xipt.mobile</groupId>
    <artifactId>quickstart_mybatis_01</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>MysqL</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.27</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.7</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.22</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>

2.创建 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>

3.新建数据表(关系)

CREATE DATABASE mybatis;
USE mybatis;
CREATE TABLE `t_account` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `username` VARCHAR(11) DEFAULT NULL,
  `password` VARCHAR(11) DEFAULT NULL,
  `age` INT(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8mb4;

4.新建数据表对应的实体类 Account(对象)

package com.xupt.mobile.domain;

import lombok.*;

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

5.通过 Mapper 代理实现⾃定义接⼝(映射)

  • ⾃定义接⼝,定义相关业务⽅法

  • 编写与⽅法相对应的 Mapper.xml

1、⾃定义接⼝
package com.xupt.mobile.dao;

import com.xupt.mobile.domain.Account;
import java.util.List;

public interface IAccount {
    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 语句
<?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.xupt.mobile.dao.IAccount">
    <insert id="save" parameterType="com.xupt.mobile.domain.Account">
        insert into t_account(username,password,age) values(#{username},#{password},#{age})
    </insert>
    <update id="update" parameterType="com.xupt.mobile.domain.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.xupt.mobile.domain.Account">
        select * from t_account
    </select>
    <select id="findById" parameterType="long"
            resultType="com.xupt.mobile.domain.Account">
        select * from t_account where id = #{id}
    </select>
</mapper>

statement 标签可根据 sql 执⾏的业务选择 insert、delete、update、select。

MyBatis 框架会根据规则⾃动创建接⼝实现类的代理对象

规则:

  • Mapper.xml 中 namespace 为接⼝的全限定类名。
  • Mapper.xml 中 statement 的 id 为接⼝中对应的⽅法名。
  • Mapper.xml 中 statement 的 parameterType 和接⼝中对应⽅法的参数类型⼀致。
  • Mapper.xml 中 statement 的 resultType 和接⼝中对应⽅法的返回值类型⼀致
3、在 config.xml 中注册 AccountMapper.xml
<mappers>
        <mapper resource="com/xupt/mobile/dao/AccountMapper.xml"></mapper>
</mappers>

6.调⽤接⼝的代理对象完成相关的业务操作

package com.xupt.mobile.test;

import com.xupt.mobile.dao.IAccount;
import com.xupt.mobile.domain.Account;
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 MybatisTest01 {
    public static void main(String[] args) {
        InputStream resourceAsstream = MybatisTest01.class.getClassLoader().getResourceAsstream("config.xml");
        sqlSessionFactoryBuilder sqlSessionFactoryBuilder = new sqlSessionFactoryBuilder();
        sqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(resourceAsstream);
        sqlSession sqlSession = sqlSessionFactory.openSession();

        //获取实现接⼝的代理对象
        IAccount IAccountImpl= sqlSession.getMapper(IAccount.class);
        IAccountImpl.save(new Account(1L,"瑞瑞学长","111111",3));
        IAccountImpl.save(new Account(2L,"璇璇学长","222222",6));
        IAccountImpl.save(new Account(3L,"杰杰学长","333333",9));
        IAccountImpl.save(new Account(4L,"琪琪学姐","444444",1));
        IAccountImpl.save(new Account(5L,"平平学姐","555555",2));
        IAccountImpl.save(new Account(4L,"佑佑学长","666666",8));

        IAccountImpl.update(new Account(4L,"佑佑学长","777777",9));
        IAccountImpl.deleteById(15);
        List<Account> list = IAccountImpl.findAll();
        for (Account account:list) {
            System.out.println(account);
        }
        IAccountImpl.findById(16);
        
        sqlSession.commit();
        sqlSession.close();
    }
}

Mapper.xml

parameterType:参数数据类型

1、基本数据类型,通过 id 查询 Account

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

2、String 类型,通过 name 查询 Account

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

3.多个参数,通过 name 和 age 查询 Account(注意#{下标1}and#{下标2})

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

resultType:结果类型

1、基本数据类型,统计 Account 总数

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

2、包装类,统计 Account 总数

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

3、String 类型,通过 id 查询 Account 的 name

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

4.Java Bean

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

级联查询

  • 一对多

Student

package com.xupt.mobile.domain;

import lombok.*;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
public class Student {
    private long id;
    private String name;
    private Classes classes;//多对一
}

Classes

package com.xupt.mobile.domain;

import lombok.*;

import java.util.List;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
public class Classes {
    private long id;
    private String name;
    List<Student> students;//一对多
}

IStudent

package com.xupt.mobile.dao;

import com.xupt.mobile.domain.Student;

public interface IStudent {
    public Student findById(Long id);
}

IClasses

package com.xupt.mobile.dao;

import com.xupt.mobile.domain.Classes;

public interface IClasses {
    public Classes findById(Long id);
}

StudentMapper.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.xupt.mobile.dao.IStudent">
    <resultMap id="studentMap" type="com.xupt.mobile.domain.Student">
        <id column="id" property="id"></id>
        <result column="name" property="name"></result>
        <!--此时实体类是个多对一,用javaType表示classes类型-->
        <association property="classes" javaType="com.xupt.mobile.domain.Classes">
            <id column="cid" property="id"></id>
            <result column="cname" property="name"></result>
        </association>
    </resultMap>

    <!--此时是笛卡尔积结果,交给studentMap-->
    <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>

ClassesMapper.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.xupt.mobile.dao.IClasses">
    <resultMap id="classesMap" type="com.xupt.mobile.domain.Classes">
        <id column="cid" property="id"></id>
        <result column="cname" property="name"></result>
        <!--此时实体类是个一对多关系,用ofType表示students的泛型类型-->
        <collection property="students" ofType="com.xupt.mobile.domain.Student">
            <id column="id" property="id"></id>
            <result column="name" property="name"></result>
        </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.xupt.mobile.domain;

import lombok.*;

import java.util.List;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@ToString
public class Customer {
    private long id;
    private String name;
    private List<Goods> goods;
}

Goods

package com.xupt.mobile.domain;

import lombok.*;

import java.util.List;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@ToString
public class Goods {
    private long id;
    private String name;
    private List<Customer> customers;
}

ICustomer

package com.xupt.mobile.dao;

import com.xupt.mobile.domain.Customer;

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

CustomerMapper.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.xupt.mobile.dao.ICustomer">
    <resultMap id="customerMap" type="com.xupt.mobile.domain.Customer">
        <id column="cid" property="id"></id>
        <result column="cname" property="name"></result>
        <collection property="goods" ofType="com.xupt.mobile.domain.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,goods g,customer_goods cg where c.id = #{id} and cg.id = c.id    
     </select>
</mapper>

GoodsMapper.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.xupt.mobile.dao.IGoods">
    <resultMap id="goodsMap" type="com.xupt.mobile.domain.Goods">
        <id column="gid" property="id"></id>
        <result column="gname" property="name"></result>
        <collection property="customers" ofType="com.xupt.mobile.domain.Customer">
            <id column="gid" property="id"></id>
            <result column="gname" property="name"></result>
        </collection>
    </resultMap>
    <select id="findById" parameterType="long" resultMap="goodsMap">
        select g.id gid,g.name gname,c.id cid,c.name cname from goods g,customer c,customer_goods cg where g.id = #{id} and cg.id = 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 配置⽂件 generatorConfifig.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&characterEncoding=UTF-8"
 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 e) {
 e.printstacktrace();
 } catch (IOException e) {
 e.printstacktrace();
 } catch (InterruptedException e) {
 e.printstacktrace();
 }
 }
}

MyBatis 延迟加载

什么是延迟加载?

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

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

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

  • 在 confifig.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.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(1L);
 System.out.println(account);
 sqlSession.close();
 sqlSession = sqlSessionFactory.openSession();
 accountRepository = sqlSession.getMapper(AccountRepository.class);
 Account account1 = accountRepository.findById(1L);
 System.out.println(account1);
 }

}
  • ⼆级缓存

1、MyBatis ⾃带的⼆级缓存

  • confifig.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.southwind.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;
}

2、ehcache ⼆级缓存

<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 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>
  • confifig.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.southwind.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 的组成。

<select id="findByAccount" parameterType="com.southwind.entity.Account"
resultType="com.southwind.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 中,如果条件不成⽴则不添加

如果条件成⽴则添加

<select id="findByAccount" parameterType="com.southwind.entity.Account"
resultType="com.southwind.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 结合起来使⽤。

<select id="findByAccount" parameterType="com.southwind.entity.Account"
resultType="com.southwind.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 标签中的 prefifix 和 suffiffiffix 属性会被⽤于⽣成实际的 sql 语句,会和标签内部的语句进⾏拼接,如果语句前后出现了 prefifixOverrides 或者 suffiffiffixOverrides 属性中指定的值,MyBatis 框架会⾃动将其删除

<select id="findByAccount" parameterType="com.southwind.entity.Account"
resultType="com.southwind.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 标签⽤于 update 操作,会⾃动根据参数选择⽣成 sql 语句

<update id="update" parameterType="com.southwind.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 标签可以迭代⽣成⼀系列值,这个标签主要⽤于 sql 的 in 语句。

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

相关文章

php输出xml格式字符串
J2ME Mobile 3D入门教程系列文章之一
XML轻松学习手册
XML入门的常见问题(一)
XML入门的常见问题(三)
XML轻松学习手册(2)XML概念