MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
<dependencies>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.4.6version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.11version>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>1.18.12version>
<scope>providedscope>
dependency>
dependencies>
use mybatis;
creat table t_account(
id int primary key auto_increment,
username varchar(11),
password varchar(11),
age int
)
import lombok.Data;
@Data
public class Account {
private long id;
private String username;
private String password;
private int age;
}
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC">transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
dataSource>
environment>
environments>
configuration>
<mapper namespace="com.toolate.mapper.AccountMapper">
<insert id="save" parameterType="com.toolate.entity.Account">
insert into t_account(username,password,age) values(#{username},#{password},#{age})
insert>
mapper>
<mappers>
<mapper resource="com/toolate/mapper/AccountMapper.xml">mapper>
mappers>
public class InsertTest {
public static void main(String[] args) {
InputStream inputStream = Insert.class.getClassLoader().getResourceAsStream("config.xml");
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
String statement = "com.toolate.mapper.AccountMapper.save";
Account account = new Account(1L, "张三", "123456", 20);
sqlSession.insert(statement,account);//将account作为参数传给sqlSession执行
sqlSession.commit();
}
}
<settings>
<setting name="logImpl" value="STDOUT_LOGGING" />
settings>
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);
}
<mapper namespace="com.toolate.repository.AccountRepository">
<insert id="save" parameterType="com.toolate.entity.Account">
insert into t_account(username,password,age) values(#{username},#{password},#{age})
insert>
<update id="update" parameterType="com.toolate.entity.Account">
update t_account set username = #{username},password = #{password},age = #{age}
update>
<delete id="deleteById" parameterType="long">
delete from t_account where id = #{id}
delete>
<select id="findAll" resultType="com.toolate.entity.Account">
select * from t_account
select>
<select id="findById" parameterType="long" resultType="com.toolate.entity.Account">
select * from t_account where id = #{id}
select>
mapper>
<mapper resource="com/toolate/repository/AccountRepository.xml">mapper>
public class test02 {
public static void main(String[] args) {
//加载配置文件
InputStream inputStream = test02.class.getClassLoader().getResourceAsStream("config.xml");
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sessionFactory = sqlSessionFactoryBuilder.build(inputStream);
SqlSession sqlSession = sessionFactory.openSession();
//获取实现方法的代理对象
AccountRepository accountRepository = sqlSession.getMapper(AccountRepository.class);
//查询全部对象
// List list = accountRepository.findAll();
// for (Account account : list) {
// System.out.println(account);
// }
//添加对象
// Account account = new Account(14L, "王五", "111111", 23);
// accountRepository.save(account);
// sqlSession.commit();
//通过id查询对象
// Account account = accountRepository.findById(13L);
// System.out.println(account);
//修改对象
// Account account = new Account(12, "小李", "654321", 25);
// int result = accountRepository.updateById(account);
// sqlSession.commit();
// System.out.println(result);
//通过id删除对象
// int result = accountRepository.deleteById(13L);
// System.out.println(result);
// sqlSession.commit();
sqlSession.close();
}
}
<select id="findById" parameterType="long" resultType="com.toolate.entity.Account">
select * from t_account where id = #{id}
select>
<select id="findByName" parameterType="String" resultType="com.toolate.entity.Account">
select * from t_account where username = #{username}
select>
<select id="findById" parameterType="java.long.Long" resultType="com.toolate.entity.Account">
select * from t_account where id = #{id}
select>
<select id="findByNameAndAge" resultType="com.toolate.entity.Account">
select * from t_account where username = #{param1} and age = #{param2}
select>
可以用param1、param2或arg0和arg1表示第一和第二个参数
<update id="update" parameterType="com.toolate.entity.Account">
update t_account set username = #{username},password = #{password},age = #{age}
update>
<select id="count" resultType="int">
select count(id) from t_account
select>
<select id="count2" resultType="java.lang.Integer">
select count(id) from t_account
select>
<select id="findNameById" resultType="java.lang.String">
select username from t_account where id = #{id}
select>
<select id="findById" parameterType="long" resultType="com.toolate.entity.Account">
select * from t_account where id = #{id}
select>
@Data
public class Student {
private long id;
private String name;
private Classes classes;
}
Classes
@Data
public class Classes {
private long id;
private String name;
private List<Student> students;
}
StudentRepository
public interface StudentRepository {
public Student findById(long id);
}
StudentRepository.xml
通过association来使两表级联查询关系相互映射
<resultMap id="studentMap" type="com.toolate.entity.Student">
<id column="id" property="id">id>
<result column="name" property="name">result>
<association property="classes" javaType="com.toolate.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>
结果如下:
Student(id=1, name=张三, classes=Classes(id=2, name=6班, students=null))
ClassesRepository
public interface ClassesRepository {
public Classes findById(long id);
}
ClassesRepository.xml
<mapper namespace="com.toolate.repository.ClassesRepository">
<resultMap id="classesMap" type="com.toolate.entity.Classes">
<id column="cid" property="id">id>
<result column="cname" property="name">result>
<collection property="students" ofType="com.toolate.entity.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>
import java.util.List;
@Data
public class Customer {
private long id;
private String name;
private List<Goods> goods;
}
Goods
import java.util.List;
@Data
public class Goods {
private long id;
private String name;
private List<Customer> customers;
}
CustomerRepository
package com.toolate.repository;
import com.toolate.entity.Customer;
public interface CustomerRepository {
public Customer findById(long id);
}
GoodsRepository
package com.toolate.repository;
import com.toolate.entity.Goods;
public interface GoodsRepository {
public Goods findById(long id);
}
CustomerRepository.xml
<mapper namespace="com.toolate.repository.CustomerRepository">
<resultMap id="customerMap" type="com.toolate.entity.Customer">
<id column="cid" property="id">id>
<result column="cname" property="name">result>
<collection property="goods" ofType="com.toolate.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, goods g,customer_goods cg where c.id = #{id} and cg.cid = c.id and cg.gid = g.id;
select>
mapper>
GoodsRepository.xml
<mapper namespace="com.toolate.repository.GoodsRepository">
<resultMap id="goodsMap" type="com.toolate.entity.Goods">
<id column="gid" property="id">id>
<result column="gname" property="name">result>
<collection property="customers" ofType="com.toolate.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, 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 需要开发者⾃⼰来完成。
<dependencies>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.4.6version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.11version>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>1.18.10version>
<scope>providedscope>
dependency>
<dependency>
<groupId>org.mybatis.generatorgroupId>
<artifactId>mybatis-generator-coreartifactId>
<version>1.3.7version>
dependency>
dependencies>
<generatorConfiguration>
<context id="testTables" targetRuntime="MyBatis3">
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8" userId="root" password="123456">jdbcConnection>
<javaModelGenerator targetPackage="com.toolate.entity" targetProject="./src/main/java">javaModelGenerator>
<sqlMapGenerator targetPackage="com.toolate.repository" targetProject="./src/main/java">sqlMapGenerator>
<javaClientGenerator type="XMLMAPPER" targetPackage="com.toolate.repository" targetProject="./src/main/java">javaClientGenerator>
<table tableName="t_user" domainObjectName="User">table>
context>
generatorConfiguration>
package com.toolate.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();
}
}
}
延迟加载也叫懒加载、惰性加载,使⽤延迟加载可以提⾼程序的运⾏效率,针对于数据持久层的操作,
在某些特定的情况下去访问特定的数据库,在其他情况下可以不访问某些表,从⼀定程度上减少了 Java
应⽤与数据库的交互次数。
查询学⽣和班级的时,学⽣和班级是两张不同的表,如果当前需求只需要获取学⽣的信息,那么查询学
⽣单表即可,如果需要通过学⽣获取对应的班级信息,则必须查询两张表。
不同的业务需求,需要查询不同的表,根据具体的业务需求来动态减少数据表查询的⼯作就是延迟加
载。
<settings>
<setting name="logImpl" value="STDOUT_LOGGING" />
<setting name="lazyLoadingEnabled" value="true"/>
settings>
public Student findByIdLazy(long id);
StudentRepository.xml
<resultMap id="studentMapLazy" type="com.toolate.entity.Student">
<id column="id" property="id"></id>
<result column="name" property="name"></result>
<association property="classes" javaType="com.toolate.entity.Classes"
select="com.toolate.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.toolate.entity.Classes">
SELECT * from classes where id = #{id}
select>
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 语句,参数也相等,则第⼀次执⾏成功之后会将数据保存到⼆级
缓存中,第⼆次可直接从⼆级缓存中取出数据。
代码
public class Test04 {
public static void main(String[] args) {
InputStream inputeStream = Test04.class.getClassLoader().getResourceAsStream("config.xml");
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputeStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
AccountRepository accountRepository = sqlSession.getMapper(AccountRepository.class);
Account account = accountRepository.findById(14L);
System.out.println(account);
sqlSession.close();
sqlSession =sqlSessionFactory.openSession();
AccountRepository accountRepository1 = sqlSession.getMapper(AccountRepository.class);
Account account1 = accountRepository1.findById(14L);
System.out.println(account1);
}
}
<setting name="cacheEnabled" value="true"/>
<cache>cache>
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.mybatisgroupId>
<artifactId>mybatis-ehcacheartifactId>
<version>1.0.0version>
dependency>
<dependency>
<groupId>net.sf.ehcachegroupId>
<artifactId>ehcache-coreartifactId>
<version>2.4.3version>
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>
<setting name="cacheEnabled" value="true"/>
<cache type="org.mybatis.caches.ehcache.EhcacheCache">
<property name="timeToIdleSeconds" value="3600"/>
<property name="timeToLiveSeconds" value="3600"/>
<property name="memoryStoreEvictionPolicy" value="LRU"/>
cache>
package com.toolate.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;
}
使⽤动态 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>
<select id="findByAccount" parameterType="com.toolate.entity.Account" resultType="com.toolate.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.toolate.entity.Account" resultType="com.toolate.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 标签中的 prefix 和 suffix 属性会被⽤于⽣成实际的 SQL 语句,会和标签内部的语句进⾏拼接,如
果语句前后出现了 prefixOverrides 或者 suffixOverrides 属性中指定的值,MyBatis 框架会⾃动将其删
除。
<select id="findByAccount" parameterType="com.toolate.entity.Account" resultType="com.toolate.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>
<update id="update" parameterType="com.toolate.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>
<select id="findByIds" parameterType="com.toolate.entity.Account" resultType="com.toolate.entity.Account">
select * from t_account
<where>
<foreach collection="ids" open="id in (" close=")" item="id" separator=",">
#{id}
foreach>
where>
select>