9、MyBatis框架——使用注解开发实现数据库增删改查操作、一级缓存、二级缓存、MyBatis实现分页
目录
一、使用注解开发实现数据库增删改查操作
1、搭建项目
2、使用注解开发操作数据库
二、一级缓存
1、一级缓存失效的情况
三、二级缓存
1、手动开启二级缓存cacheEnabled
2、二级缓存机制
四、MyBatis实现分页
1、配置环境
2、startPage()开启分页
3、PageInfo查询分页信息
(1)PageInfo对象
(2) getList()方法
(3)getTotal()方法
一、使用注解开发实现数据库增删改查操作
不通过mapper配置文件,通过注解实现数据库增删改查操作
1、搭建项目
(1)创建数据库表admin
CREATE DATABASE mybatisdatabase;
USE mybatisdatabase;
CREATE TABLE IF NOT EXISTS `admin`(
`uid` INT PRIMARY KEY AUTO_INCREMENT,
`username` VARCHAR(20),
`upassword` VARCHAR(20) NOT NULL,
`phone` VARCHAR(11) UNIQUE NOT NULL,
`address` VARCHAR(10) NOT NULL
);INSERT INTO `admin`(`username`,`upassword`,`phone`,`address`) VALUES
('张三','123456','15689609560','安徽合肥包河区'),
('王二','666666','13395581841','安徽合肥蜀山区'),
('李四','456789','18144172517','安徽合肥高新区');
(2)新建module--->java框架Maven工程--->完善工程目录
(3) 在pom.xml中添加需要使用的依赖
<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.mybatis</groupId><artifactId>mybayis06</artifactId><version>1.0-SNAPSHOT</version><packaging>jar</packaging><name>mybayis06</name><url>http://maven.apache.org</url><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencies><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.11</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.48</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.24</version></dependency><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version></dependency></dependencies>
</project>
(4)创建实体类和Mapper接口
package com.mybatis.entity;import lombok.Data;@Data
public class Admin {private long uid;private String username;private String upassword;private String phone;private String address;}
(5)在resources目录下新建config文件,存放mybatis全局配置文件和外部数据源
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><!-- 引入外部数据源参数--><properties resource="config/jdbc.properties"></properties><settings><!-- 开启驼峰映射--><setting name="mapUnderscoreToCamelCase" value="true"/><!-- 开启日志打印--><setting name="logImpl" value="LOG4J"/></settings><!-- 给表起别名--><typeAliases><package name="com.mybatis.entity"/></typeAliases><environments default="development"><environment id="development"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="${jdbc.driver}"/><property name="url" value="${jdbc.url}"/><property name="username" value="${jdbc.username}"/><property name="password" value="${jdbc.password}"/></dataSource></environment></environments><mappers><package name="com.mybatis.mapper"/></mappers>
</configuration>
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/mybatisdatabase
jdbc.username=root
jdbc.password=123456
(6)在resources目录下新建与Mapper接口层级相同的文件夹存放Mapper映射文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mybatis.mapper.AdminMapper"></mapper>
(7)在resources目录下添加日志配置文件log4j.properties
#打印日志的级别:可控制打印信息,哪些打印,哪些不打印
#Console:打印窗口
log4j.rootLogger=DEBUG,Console
#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Target=System.out
#设置打印格式
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
#设置打印信息
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
#打印日志级别:设置打印级别只要不是ERROR级别就不打印
log4j.logger.org.apache=ERROR
log4j.logger.org.mybatis=ERROR
log4j.logger.org.springframework=ERROR
#这个需要
log4j.logger.log4jdbc.debug=ERROR
log4j.logger.com.gk.mapper=ERROR
log4j.logger.jdbc.audit=ERROR
log4j.logger.jdbc.resultset=ERROR
#这个打印SQL语句非常重要
log4j.logger.jdbc.sqlonly=DEBUG
log4j.logger.jdbc.sqltiming=ERROR
log4j.logger.jdbc.connection=FATAL
2、使用注解开发操作数据库
在Mapper接口的方法上直接使用相应的注解来完成对数据库的操作
package com.mybatis.mapper;import com.mybatis.entity.Admin;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;import java.util.List;public interface AdminMapper {@Select("select * from admin where uid = #{uid}")public Admin selectByUid(int uid);@Select("select * from admin")public List<Admin> selectAll();@Insert("insert into admin(username,upassword,phone,address) values (#{username},#{upassword},#{phone},#{address})")public Integer insert(Admin admin);@Delete("delete from admin where uid = #{uid}")public Integer delete(int uid);@Update("update admin set username = #{username},upassword = #{upassword},phone = #{phone},address = #{address} where uid = #{uid}")public Integer update(Admin admin);
}
package com.mybatis.mapper;import com.mybatis.entity.Admin;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;import java.io.IOException;
import java.io.InputStream;
import java.util.List;import static org.junit.Assert.*;public class AdminMapperTest {SqlSessionFactory sqlSessionFactory = null;@Beforepublic void init(){InputStream resourceAsStream = null;try {resourceAsStream = Resources.getResourceAsStream("config/mybatis-config.xml");} catch (IOException e) {e.printStackTrace();}sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);}@Testpublic void selectByUid() {//创建sqlSession会话SqlSession sqlSession = sqlSessionFactory.openSession();//获取AdminMapper接口动态代理对象AdminMapper mapper = sqlSession.getMapper(AdminMapper.class);//通过接口调用方法Admin admin = mapper.selectByUid(1);System.out.println("admin = " + admin);//关闭资源sqlSession.close();}@Testpublic void selectAll() {//创建sqlSession会话SqlSession sqlSession = sqlSessionFactory.openSession();//获取AdminMapper接口动态代理对象AdminMapper mapper = sqlSession.getMapper(AdminMapper.class);//通过接口调用方法List<Admin> adminList = mapper.selectAll();for (Admin admin : adminList) {System.out.println("admin = " + admin);}//关闭资源sqlSession.close();}@Testpublic void insert() {//创建sqlSession会话,开启事务自动提交SqlSession sqlSession = sqlSessionFactory.openSession(true);//获取AdminMapper接口动态代理对象AdminMapper mapper = sqlSession.getMapper(AdminMapper.class);//创建Admin对象Admin admin = new Admin();admin.setUsername("老六");admin.setUpassword("666666");admin.setPhone("19144756263");admin.setAddress("老北京");//通过接口调用方法Integer line = mapper.insert(admin);System.out.println("line = " + line);//关闭资源sqlSession.close();}@Testpublic void delete() {//创建sqlSession会话,开启事务自动提交SqlSession sqlSession = sqlSessionFactory.openSession(true);//获取AdminMapper接口动态代理对象AdminMapper mapper = sqlSession.getMapper(AdminMapper.class);//通过家口调用方法Integer line = mapper.delete(2);System.out.println("line = " + line);//关闭资源sqlSession.close();}@Testpublic void update() {//创建sqlSession会话,开启事务自动提交SqlSession sqlSession = sqlSessionFactory.openSession(true);//获取AdminMapper接口动态代理对象AdminMapper mapper = sqlSession.getMapper(AdminMapper.class);//创建Admin对象Admin admin = new Admin();admin.setUsername("老马");admin.setUpassword("666666");admin.setPhone("18874151577");admin.setAddress("安徽芜湖");admin.setUid(3);//通过接口调用方法Integer line = mapper.update(admin);System.out.println("line = " + line);//关闭资源sqlSession.close();}
}
二、一级缓存
MyBatis一级缓存是默认开启的,在一次SqlSession会话下有效。执行两次相同查询时,为了缓解服务器的压力,第二次的查询结果来自MyBatis的缓存,不再将查询指向数据库
package com.mybatis.mapper;import com.mybatis.entity.Admin;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;import java.io.IOException;
import java.io.InputStream;
import java.util.List;public class SelectTest {SqlSessionFactory sqlSessionFactory = null;@Beforepublic void init(){InputStream resourceAsStream = null;try {resourceAsStream = Resources.getResourceAsStream("config/mybatis-config.xml");} catch (IOException e) {e.printStackTrace();}sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);}@Testpublic void selectAll() {//创建sqlSession会话SqlSession sqlSession = sqlSessionFactory.openSession();//获取AdminMapper接口动态代理对象AdminMapper mapper = sqlSession.getMapper(AdminMapper.class);//通过接口调用方法//第一次查询List<Admin> adminList = mapper.selectAll();for (Admin admin : adminList) {System.out.println("admin = " + admin);}//第二次查询List<Admin> adminList1 = mapper.selectAll();System.out.println("adminList1 = " + adminList1);//关闭资源sqlSession.close();}
}
在程序中调用了两次selectAll()方法,却只执行了一次SQL语句
1、一级缓存失效的情况
(1)执行的查询条件不同,或者SQL语句不同;
(2)两次相同的SQL语句查询之间,做了增删改的操作
(3)手动提交事务也会清空一级缓存;
(4)手动清空缓存:clearCache()
三、二级缓存
一级缓存只在一次SqlSession会话有效,为进一步扩大数据共享的范围,缓解数据库的压力,可手动开启MyBatis二级缓存
写入二级缓存的实例对象需要实现序列化接口
1、手动开启二级缓存cacheEnabled
在MyBatis全局配置文件中,设置<setting>标签
cacheEnabled:全局性地开启或关闭所有映射器配置文件中已配置的任何缓存
<!-- 全局开启二级缓存--><setting name="cacheEnabled" value="true"/>
在mapper映射文件中添加cache标签
2、二级缓存机制
(1)手动提交事务,会将一级缓存写入二级缓存;
(2)SqlSession会话对象关闭时,会将一级缓存写入二级缓存。
四、MyBatis实现分页
1、配置环境
(1)在pom.xml中引入pagehelper依赖
<dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper</artifactId><version>5.3.2</version></dependency>
(2)在mybatis全局配置文件中添加plugins标签
<plugins><plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin></plugins>
2、startPage()开启分页
在调用方法查询记录之前,调用PageHelper类中的startPage()方法开启分页:
pageNum:当前页码;
pageSize:每页显示的数量
3、PageInfo查询分页信息
(1)PageInfo对象
创建PageInfo对象,PageInfo有参构造的参数为查询获取的集合,直接输出PageInfo对象为分页信息导航
(2) getList()方法
获取当前页面的分页信息
(3)getTotal()方法
总记录数
package com.mybatis.mapper;import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mybatis.entity.Admin;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;import java.io.IOException;
import java.io.InputStream;
import java.util.List;public class SelectTest {SqlSessionFactory sqlSessionFactory = null;@Beforepublic void init(){InputStream resourceAsStream = null;try {resourceAsStream = Resources.getResourceAsStream("config/mybatis-config.xml");} catch (IOException e) {e.printStackTrace();}sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);}@Testpublic void selectAll() {//创建sqlSession会话SqlSession sqlSession = sqlSessionFactory.openSession();//获取AdminMapper接口动态代理对象AdminMapper mapper = sqlSession.getMapper(AdminMapper.class);//开启分页//pageNum:当前页码;pageSize:每页显示数量PageHelper.startPage(1,5);//通过接口调用方法List<Admin> adminList = mapper.selectAll();for (Admin admin : adminList) {System.out.println("admin = " + admin);}PageInfo<Admin> adminPageInfo = new PageInfo<>(adminList);System.out.println("adminPageInfo = " + adminPageInfo);long total = adminPageInfo.getTotal();System.out.println("total = " + total);List<Admin> list = adminPageInfo.getList();System.out.println("list = " + list);//关闭资源sqlSession.close();}
}