一.概述
1.简介
MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。2013年11月迁移到Github。
2.特点
- MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。
- MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。
- MyBatis 可以使用简单的 XML 或注解来配置和映射原生类型、接口和 Java 的 POJO为数据库中的记录。
二.用法
1.搭建环境
(1)创建数据库
CREATE DATABASE `mybatis`;
USE `mybatis`;
CREATE TABLE `user`(
`id` INT(10) NOT NULL PRIMARY KEY,
`name` VARCHAR(20) DEFAULT NULL,
`pwd` VARCHAR(20) DEFAULT NULL
)ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO `user` VALUES(1,'张三','111111'),(2,'李四','222222'),(3,'王五','333333'`user`);
(2)新建项目
- 新建一个普通的maven项目
- 删除src目录
- 在pom.xml 中导入maven依赖
<!--导入依赖-->
<dependencies>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version><!--根据自己的数据库版本自行选择对应的版本-->
</dependency>
<!--mybatis-->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
- 在maven下再次新建一个普通的maven项目在此maven中写代码
2.编写mybatis常规配置文件
(1)在resources文件夹中编写mybatis核心配置文件
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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
<!--jdbc中的url &类似于&-->
<property name="username" value="root"/><!--数据库用户名称 -->
<property name="password" value="123456"/><!--数据库用户密码 -->
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/yl/dao/UserMapper.xml"/>
</mappers>
</configuration>
(2)在java目录中的untils包中编写工具类
package com.yl.untils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.io.Resources;
import java.io.InputStream;
public class MybatisUntils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
//使用Mybatis第一步:获取sqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}catch (Exception e){
e.printStackTrace();
}
}
//在SqlSessionFactory中获得 SqlSession 的实例
// SqlSession 完全包含了面向数据库执行 SQL 命令所需的所有方法。
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
3.编写代码(mybatis对数据库的增删改查)
(1)在pojo包中编写实体类
package com.yl.pojo;
public class User {
private int id;
private String name;
private String pwd;
public User() {
}
public User(int id, String name, String pwd) {
this.id = id;
this.name = name;
this.pwd = pwd;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", pwd='" + pwd + '\'' +
'}';
}
}
(2)编写接口和接口的映射
在dao包中编写UserMapper接口
package com.yl.dao;
import com.yl.pojo.User;
import java.util.List;
import java.util.Map;
public interface UserMapper {
List<User> getUserList();//查询所有用户
User getUserByID(int id);//查询指定id的用户
List<User> getUserID(Map map);//模糊查询
int addUser(User user);//添加用户
int updateUser(User user);//修改用户
int deleteUser(int id);//删除用户
}
在dao包中编写UserMapper.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.yl.dao.UserMapper">
<select id="getUserList" resultType="com.yl.pojo.User">
select * from mybatis.user </select>
<select id="getUserByID" parameterType="int" resultType="com.yl.pojo.User">
select * from mybatis.user where id=#{id};
</select>
<select id="getUserID" parameterType="map" resultType="com.yl.pojo.User">
select * from mybatis.user where name like "%"#{username}"%";
</select>
<insert id="addUser" parameterType="com.yl.pojo.User">
insert into mybatis.user (id, name, pwd) values (#{id},#{name},#{pwd});
</insert>
<update id="updateUser" parameterType="com.yl.pojo.User">
update mybatis.user set name=#{name},pwd=#{pwd} where id=#{id};
</update>
<delete id="deleteUser" parameterType="com.yl.pojo.User">
delete from mybatis.user where id=#{id};
</delete>
</mapper>
(3)编写测试类
package com.yl.dao;
import com.yl.pojo.User;
import com.yl.untils.MybatisUntils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.HashMap;
import java.util.List;
public class UserDaoTest {
@Test
public void test(){
List<User> userList = MybatisUntils.getSqlSession().getMapper(UserMapper.class).getUserList();
for (User user : userList) {
System.out.println(user);
}
MybatisUntils.getSqlSession().close();
}
@Test
public void test2(){
SqlSession sqlSession = MybatisUntils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User id = mapper.getUserByID(3);
System.out.println(id);
sqlSession.close();
}
@Test
public void test3(){
SqlSession sqlSession = MybatisUntils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.addUser(new User(5,"赵七","123456"));
sqlSession.commit();//增删改必须提交
sqlSession.close();
}
@Test
public void test4(){
SqlSession sqlSession = MybatisUntils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.updateUser(new User(3,"王五","333333"));
sqlSession.commit();
sqlSession.close();
}
@Test
public void test5(){
SqlSession sqlSession = MybatisUntils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.deleteUser(4);
sqlSession.commit();
sqlSession.close();
}
@Test
public void test6(){
SqlSession sqlSession = MybatisUntils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
HashMap map = new HashMap();
map.put("username","赵");
List<User> userID = mapper.getUserID(map);
for (User user : userID) {
System.out.println(user);
}
sqlSession.close();
}
}
三.配置
1.属性(properties)
注意 :properties必须写在configuration中的最前面,否则会报错
通过properties外部配置property中的value
注意 :也可以写在内部,不过优先级没有外部高
(1)在resources下建立db.properties文件
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8
username=root
password=123456
(2)简写property中的value
<?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>
<properties resource="db.properties">
<property name="username" value="root"/>
<property name="password" value="111111"/>
</properties>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<!--<mapper resource="com/yl/dao/UserMapper.xml"/>-->
<mapper class="com.yl.dao.UserMapper"></mapper>
</mappers>
</configuration>
2.类型别名
在mybatis-config.xml中的properties下方添加如下代码
<typeAliases>
<typeAlias type="com.yl.pojo.User" alias="user"></typeAlias>
</typeAliases>
这样dao包中编写UserMapper.xml中的resultType就可以简写
<select id="getUserList" resultType="user">
select * from mybatis.user </select>
如果实体类与数据库中的字段不对应可以做出以下优化
例:误把数据库中的pwd写为password
在UserMapper.xml中做如下优化,用resultMap代替resultType
<resultMap id="Usermap" type="user">
<result column="pwd" property="password"></result>
</resultMap>
<select id="getUserList" resultMap="Usermap">
select * from mybatis.user </select>
这样就可以避免与数据库字段不对应而导致查询为空的情况
3.映射器
(1)使用相对于类路径的资源引用
<mappers>
<mapper resource="com/yl/dao/UserMapper.xml"/>
</mappers>
(2)使用映射器接口实现类的完全限定类名
<mappers>
<mapper class="com.yl.dao.UserMapper"></mapper>
</mappers>
(3)将包内的映射器接口实现全部注册为映射器
<mappers>
<package name="com.yl.dao"></package>
</mappers>
注意 :接口和配置文件必须同名且在同一包下
四.作用域(Scope)和生命周期
生命周期和作用域是至关重要的,因为错误的使用会导致非常严重的并发问题。
1.SqlSessionFactoryBuilder
这个类可以被实例化、使用和丢弃,一旦创建了 SqlSessionFactory,就不再需要它了
你可以重用 SqlSessionFactoryBuilder 来创建多个 SqlSessionFactory 实例,但是最好还是不要让其一直存在。
相当于局部变量
2.SqlSessionFactory
-
SqlSessionFactory 一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例。
-
使用 SqlSessionFactory 的最佳实践是在应用运行期间不要重复创建多次
-
SqlSessionFactory 的最佳作用域是应用作用域
-
有很多方法可以做到,最简单的就是使用单例模式或者静态单例模式。
可以把它想象为数据库连接池
3.SqlSession
- 连接到连接池的一个请求
- 每个线程都应该有它自己的 SqlSession 实例。SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域。
- 用完之后要赶紧关闭,否则资源会被占用
这里的每一个Mapper就代表一个业务
五.日志
Mybatis 的内置日志工厂提供日志功能,内置日志工厂将日志交给以下其中一种工具作代理:
- SLF4J
- Apache Commons Logging
- Log4j 2
- Log4j
- JDK logging
- STDOUT_LOGGING
- NO_LOGGING
1.STDOUT_LOGGING标准日志的使用
- (1)在mybatis核心配置文件中配置日志
- (2)正常运行即可使用
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
2.log4j的使用
Log4j是Apache的一个开源项目,通过使用Log4j可以把日志信息在控制台输出,
我们也可以控制每一条日志的输出格式,通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程。
可以通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。
(1)导入log4j的包
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
(2)在resources包中导入log4j.properties
#将等级为DEBUG的日志信息输出到console和file这两个目的地,console和file的定义在下面的代码
log4j.rootLogger=DEBUG,console,file
#控制台输出的相关设置
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%c]-%m%n
#文件输出的相关设置
log4j.appender.file = org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./log/kuang.log
log4j.appender.file.MaxFileSize=10mb
log4j.appender.file.Threshold=DEBUG
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n
#日志输出级别
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
(3)在mybatis核心配置文件中配置log4j日志
<settings>
<setting name="logImpl" value="LOG4J"/>
</settings>
(4)在要输出日志的类中加入相关语句
1.定义属性
static Logger logger = Logger.getLogger(LogDemo.class); //LogDemo为相关的类
2.日志的级别
logger.info("info进入了");
logger.debug("debug进入了");
logger.error("error进入了");
六.分页
使用分页可以减少数据的处理量
1.使用Limit分页
假设有一个学生表,对这个表进行分页
(1)编写接口
List<Student> getStudentLimit(Map map);
(2)编写接口对应的配置文件
<select id="getStudentLimit" parameterType="map" resultType="student">
select * from mybatis.student limit #{s1},#{s2};
</select>
(3)编写测试类
@Test
public void test2(){
SqlSession sqlSession = MybatisUntils.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
HashMap map = new HashMap();
map.put("s1",2);
map.put("s2",3);
List<Student> limit = mapper.getStudentLimit(map);
for (Student student : limit) {
System.out.println(student);
}
sqlSession.close();
}
2.RowBounds分页
假设有一个学生表,对这个表进行分页
(1)编写接口
List<Student> getStudentRowBounds();
(2)编写接口对应的配置文件
<select id="getStudentRowBounds" resultType="student">
select * from mybatis.student;
</select>
(3)编写测试类
@Test
public void test3(){
SqlSession sqlSession = MybatisUntils.getSqlSession();
RowBounds rowBounds = new RowBounds(2, 3);
List<Student> list = sqlSession.selectList("com.yl.dao.StudentMapper.getStudentRowBounds", null, rowBounds);
for (Student student : list) {
System.out.println(student);
}
sqlSession.close();
}
七.注解
1.注解的使用
(1)在接口上实现注解
@Select("select * from mybatis.student ")
List<Student> getStudent();
(2)在核心配置文件中绑定接口
<mappers>
<mapper class="com.yl.dao.StudentMapper"/>
</mappers>
(3)编写测试类
@Test
public void test(){
SqlSession sqlSession = MybatisUntils.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
List<Student> student = mapper.getStudent();
for (Student student1 : student) {
System.out.println(student1);
}
sqlSession.close();
}
2.注解的增删改查
public interface StudentMapper {
@Select("select * from mybatis.student ")
List<Student> getStudent();
@Select("select * from user where id = #{id}")
Student getStudentByID(@Param("id") int id);
@Insert("insert into user(id,name,age) values (#{id},#{name},#{age})")
int addStudent(Student student);
@Update("update user set name=#{name},age=#{age} where id = #{id}")
int updateStudent(Student student);
@Delete("delete from user where id = #{id}")
int deleteStudent(@Param("id") int id);
}
注意:
在遇到基本类型的参数或者String类型,需要加上@Param,
引用类型不需要加,
如果只有一个基本类型的话,可以忽略。
如果方法存在多个参数,所有的参数前面必须加上 @Param(“id”)注解,
@Param中的属性名可以用自己喜欢的字母代替,但写测试类时要与自定义的字符一致,
因为我们在SQL中引用的就是我们这里的 @Param() 中设定的属性名。
八.Lombok
在项目中使用Lombok可以减少很多重复代码的书写。比如说getter/setter/toString等方法的编写
1.Lombok在IDEA中的的安装
- (1)打开IDEA的Setting
- (2)选择Plugins选项
- (3)搜索Lombok
- (4)下载安装后重启IDEA
- (5)在项目中导入Lombok的jar包
- (6)在实体类上添加注解
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
</dependency>
2.Lombok的一些注解
- @Getter and @Setter
- @FieldNameConstants
- @ToString
- @EqualsAndHashCode
- @AllArgsConstructor:有参构造
- @RequiredArgsConstructor
- @NoArgsConstructor:无参构造
- @Log: @Log4j, @Log4j2, @Slf4j, @XSlf4j, @CommonsLog, @JBossLog, @Flogger
- @Data:包括getter、setter、equals、canEqual、hashCode、toString方法
- @Builder
- @Singular
- @Delegate
- @Value
- @Accessors
- @Wither
- @SneakyThrows
九.多对一与一对多
1.数据库的创建
CREATE TABLE `teacher` (
`id` INT(10) NOT NULL,
`name` VARCHAR(30) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8
INSERT INTO teacher(`id`, `name`) VALUES (1, '秦老师');
CREATE TABLE `student` (
`id` INT(10) NOT NULL,
`name` VARCHAR(30) DEFAULT NULL,
`tid` INT(10) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fktid` (`tid`),
CONSTRAINT `fktid` FOREIGN KEY (`tid`) REFERENCES `teacher` (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('1', '小明', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('2', '小红', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('3', '小张', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('4', '小李', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('5', '小王', '1');
2.环境的搭建
(1)搭建步骤
- (1)导入lombok、log4j.properties
- (2)新建实体类 Teacher,Student
- (3)建立Mapper接口
- (4)建立Mapper.XML文件
- (5)在核心配置文件中绑定注册我们的Mapper接口和文件
(2)代码实现
实体类的创建
Teacher实体类
@Data
public class Teacher {
private int id;
private String name;
}
Student实体类
@Data
public class Student {
private int id;
private String name;
private Teacher teacher;
}
接口的创建
public interface StudentMapper {
List<Student> getStudent();
List<Student> getStudent2();
public interface TeacherMapper {
}
配置文件的创建
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.yl.dao.StudentMapper">
</mapper>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.yl.dao.TeacherMapper">
</mapper>
核心配置文件
<?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>
<properties resource="db.properties"></properties>
<settings>
<setting name="logImpl" value="LOG4J"/>
</settings>
<typeAliases>
<typeAlias type="com.yl.pojo.Student" alias="student" />
<typeAlias type="com.yl.pojo.Teacher" alias="teacher" />
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name="com.yl.dao" />
</mappers>
</configuration>
db.properties文件
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8
username=root
password=123456
3.多对一测试
编写StudentMapper.xml文件,代码如下:
(1)按查询嵌套处理
<select id="getStudent" resultMap="StudentTeacher">
select * from mybatis.student
</select>
<resultMap id="StudentTeacher" type="Student">
<result property="id" column="id" />
<result property="name" column="name" />
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher" />
</resultMap>
<select id="getTeacher" resultType="teacher">
select * from mybatis.teacher where id=#{id}
</select>
(2)按照结果嵌套处理
<select id="getStudent2" resultMap="StudentTeacher2">
select s.id sid,s.name sname,t.name tname
from mybatis.student s,mybatis.teacher t where s.tid=t.id;
</select>
<resultMap id="StudentTeacher2" type="student">
<result property="id" column="sid" />
<result property="name" column="sname" />
<association property="teacher" javaType="teacher">
<result property="name" column="tname" />
</association>
</resultMap>
(3)编写测试类测试即可(以上两种处理方法任选其一)
4.一对多测试
(1)重新搭建环境
改变实体类
Teacher实体类
@Data
public class Teacher {
private int id;
private String name;
private List<Student> students;
}
Student实体类
@Data
public class Student {
private int id;
private String name;
private int tid;
}
(2)编写TeacherMapper.xml文件
按查询嵌套处理
<select id="getTeacher" resultMap="TeacherStudent">
select * from mybatis.teacher where id = #{tid}
</select>
<resultMap id="TeacherStudent" type="teacher">
<collection property="students" javaType="ArrayList" ofType="student" select="getStudentByTeacherId" column="id"/>
</resultMap>
<select id="getStudentByTeacherId" resultType="student">
select * from mybatis.student where tid = #{tid}
</select>
按结果嵌套查询
<select id="getTeacher2" resultMap="TeacherStudent2">
select s.id sid, s.name sname, t.name tname,t.id tid
from student s,teacher t
where s.tid = t.id and t.id = #{tid}
</select>
<resultMap id="TeacherStudent2" type="teacher">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<collection property="students" ofType="student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<result property="tid" column="tid"/>
</collection>
</resultMap>
5.对比
(1)多对一
用关联association
其中JavaType 用来指定实体类中属性的类型
(2)一对多
用集合collection
其中ofType 用来指定映射到List或者集合中的 pojo类型,泛型中的约束类型!
十.动态 SQL
动态SQL就是指根据不同的条件生成不同的SQL语句
1.创建数据库表单
CREATE TABLE `blog` (
`id` varchar(50) NOT NULL COMMENT '博客id',
`title` varchar(100) NOT NULL COMMENT '博客标题',
`author` varchar(30) NOT NULL COMMENT '博客作者',
`create_time` datetime NOT NULL COMMENT '创建时间',
`views` int(30) NOT NULL COMMENT '浏览量'
) ENGINE=InnoDB DEFAULT CHARSET=utf8
此表单无数据,需自行添加数据
2.创建工程框架
- (1)导入lombok、log4j.properties
- (2)新建实体类 Blog
- (3)建立Mapper接口
- (4)建立Mapper.XML文件
- (5)在核心配置文件中绑定注册Mapper接口和文件
实体类的创建
@Data
public class Blog {
private int id;
private String title;
private String author;
private Date createTime;
private int views;
}
3.动态sql的使用
(1)if与where的使用
where可以根据需要自动去除and
创建接口
List<Blog> BlogIf(Map map);
对应的配置文件
<select id="BlogIf" parameterType="map" resultType="Blog">
select * from mybatis.blog
<where>
<if test="title != null">
and title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</where>
</select>
(2)if与set的使用
set可以根据需要自动去除逗号
创建接口
int updateBlog(Map map);
对应的配置文件
<update id="updateBlog" parameterType="map">
update mybatis.blog
<set>
<if test="title != null">
title = #{title},
</if>
<if test="author != null">
author = #{author}
</if>
</set>
where id = #{id}
</update>
(3)when和otherwise的使用
创建接口
List<Blog> BlogChoose(Map map);
对应的配置文件
<select id="BlogChoose" parameterType="map" resultType="Blog">
select * from mybatis.blog
<where>
<choose>
<when test="title != null">
title = #{title}
</when>
<when test="author != null">
and author = #{author}
</when>
<otherwise>
and views = #{views}
</otherwise>
</choose>
</where>
</select>
(4)遍历集合
创建接口
List<Blog> blogForeach(Map map);
对应的配置文件
<select id="blogForeach" parameterType="map" resultType="Blog">
select * from mybatis.blog
<where>
<foreach collection="ids" item="id" open="and (" close=")" separator="or">
id=#{id}
</foreach>
</where>
</select>
测试类
@Test
public void blogForeach(){
SqlSession sqlSession = MybatisUntils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
ArrayList<Integer> ids = new ArrayList<Integer>();
ids.add(1);
ids.add(2);
ids.add(3);
map.put("ids",ids);
List<Blog> blogs = mapper.blogForeach(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}
4.动态sql的复用
(1)抽取复用片段
<sql id="update">
<if test="title != null">
title = #{title},
</if>
<if test="author != null">
author = #{author}
</if>
</sql>
(2)在需要的地方引用
<update id="updateBlog" parameterType="map">
update mybatis.blog
<set>
<include refid="update"></include>
</set>
where id = #{id}
</update>
十一.Mybatis缓存
1.关于缓存的介绍
(1)描述
在进行查询的时候不断地连接数据库比较耗资源,
因此可以把一次查询的结果,给他暂存在一个可以直接取到的地方,即缓存
当我们再次查询相同数据的时候,直接走缓存,就不用走数据库,
(2)优点
它可以减少和数据库的交互次数,减少系统开销,提高系统效率。
(3)适用对象
对于经常查询并且不经常改变的数据可以使用缓存
(4)在MyBatis中的应用
MyBatis包含一个非常强大的查询缓存特性,它可以非常方便地定制和配置缓存,极大的提升查询效率。
分类
MyBatis系统中默认定义了两级缓存:一级缓存和二级缓存
2.一级缓存
一级缓存也称本地缓存:SqlSession
与数据库同一次会话期间查询到的数据会放在本地缓存中。
一级缓存默认是开启的,只在一次SqlSession中有效,也就是拿到连接到关闭连接这个区间段
可以把一级缓存看成一个Map
3.二级缓存
二级缓存也叫全局缓存,作用域比一级缓存高
所有数据存只会被存放在一级缓存中,当会话关闭时才会被提交到二级缓存
二级缓存是基于namespace级别的缓存,一个名称空间,对应一个二级缓存
(1)工作机制
- 一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中;
- 如果当前会话关闭,这个会话对应的一级缓存会把缓存信息存到二级缓存后关闭一级缓存
- 新的会话查询信息,就可以从二级缓存中获取查询的内容
不同的mapper查出的数据会放在自己对应的缓存(map)中
(2)开启方式
在核心配置文件中设置
<!--显示的开启全局缓存-->
<setting name="cacheEnabled" value="true"/>
在要使用二级缓存的Mapper中开启
可以不设置参数只写以下代码
<cache/>
也可以自定义参数
<cache eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"/>
注意使用时需要将实体类序列化!否则就会报错
4.自定义缓存(ehcache)
(1)导入依赖
<!-- https://mvnrepository.com/artifact/org.mybatis.caches/mybatis-ehcache -->
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.1.0</version>
</dependency>
(2)在mapper中设置
<!--在当前Mapper.xml中使用二级缓存-->
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
(3)在resources包下建立ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false">
<diskStore path="./tmpdir/Tmp_EhCache"/>
<defaultCache
eternal="false"
maxElementsInMemory="10000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="1800"
timeToLiveSeconds="259200"
memoryStoreEvictionPolicy="LRU"/>
<cache
name="cloud_user"
eternal="false"
maxElementsInMemory="5000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="1800"
timeToLiveSeconds="1800"
memoryStoreEvictionPolicy="LRU"/>
</ehcache>
(4)正常使用即可
5.缓存失效
有以下几种情况可能导致缓存失效
-
查询不同的东西
-
增删改操作,可能会改变原来的数据,所以必定会刷新缓存!
-
查询不同的Mapper.xml
-
手动清理缓存
//手动清理缓存
sqlSession.clearCache();