Mybatis
如何获得Mybatis?
maven仓库:
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
Github:https://github.com/mybatis/mybatis-3/releases
中文文档:https://mybatis.org/mybatis-3/zh/index.html
持久化
数据持久化
- 持久化就是将程序的数据在持久化状态和瞬时状态转化的过程
- 内存:断电即失
- 数据库(jdbc),io文件持久化。
- 生活:冷藏
为什么需要持久化?
- 有一些对象,不能让他丢掉
- 内存太贵了
持久层
Dao层,Service层,Controller层……
- 完成持久化工作的代码块
- 层界限十分明显
搭建环境
搭建数据库
CREATE DATABASE `mybatis`;
USE `mybatis`;
CREATE TABLE `user`(
`id` INT(20) NOT NULL PRIMARY KEY,
`name` VARCHAR(30) DEFAULT NULL,
`pwd` VARCHAR(30) DEFAULT NULL
) ENGINE = INNODB DEFAULT CHARSET = utf8;
INSERT INTO `user`(id, `name`,`pwd`) VALUES
(1,'狂神','123456'),
(2,'张三','123456'),
(3,'李四','123456')
新建项目
-
新建一个普通的Maven项目
-
删除src目录
-
<!--导入依赖--> <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.7</version> </dependency> <!-- Junit--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> </dependencies>
创建一个模块
-
编写mybatis核心配置文件
<?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?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT"/> <property name="username" value="root"/> <property name="password" value="201103"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/kuang/dao/UserMapper.xml"></mapper> </mappers> </configuration>
-
编写mybatis工具类
package com.kuang.utils; 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 java.io.IOException; import java.io.InputStream; //sqlSessionFactory--》sqlSession public class MybatisUtils { private static SqlSessionFactory sqlSessionFactory; static { try { //使用Mybatis获取sqlSessionFactory对象 String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } public static SqlSession getSqlSession(){ return sqlSessionFactory.openSession(); } }
-
编写代码
-
实体类
package com.kuang.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 + '\'' + '}'; } }
-
Dao接口
package com.kuang.dao; import com.kuang.pojo.User; import java.util.List; public interface UserDao { List<User> getUserList(); }
-
接口实现类由原来的UserDaoImpl转变为一个Mapper配置文件
<?xml version="1.0" encoding="UTF-8" ?> select * from mybatis.user; -
测试
注意点:package com.kuang.dao; import com.kuang.pojo.User; import com.kuang.utils.MybatisUtils; import org.apache.ibatis.session.SqlSession; import org.junit.Test; import java.util.List; public class UserDaoTest { @Test public void test() { // SqlSession sqlSession = MybatisUtils.getSqlSession(); SqlSession sqlSession = MybatisUtils.getSqlSession(); //执行sql UserDao mapper = sqlSession.getMapper(UserDao.class); List<User> userList = mapper.getUserList(); for (User user: userList) { System.out.println(user); } //关闭sqlSession sqlSession.close(); } }
-
-
CRUD
namespace
namespace中的包名要和Dao/mapper接口的包名一致
select
选择、查询语句
- id:就是对应的namespace对应的方法名;
- resultType:Sql语句执行的返回值!
- paramterType:参数类型!
-
编写接口
//根据ID查询用户 User getUserById(int id);
-
编写对应的mapper中的sql语句
<select id="getUserById" parameterType="int" resultType="com.kuang.pojo.User"> select * from mybatis.user where id = #{id} </select>
-
测试
@Test public void getUserById() { SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user = mapper.getUserById(1); System.out.println(user); sqlSession.close(); }
insert
!-- 对象中的属性可以直接取出来--> <insert id="addUser" parameterType="com.kuang.pojo.User"> insert into mybatis.user (id, name, pwd) values(#{id},#{name},#{pwd}) </insert>
update
<update id="updateUser" parameterType="com.kuang.pojo.User"> update mybatis.user set name = #{name}, pwd = #{pwd} where id = #{id} </update>
delete
<delete id="deleteUser" parameterType="int"> delete from mybatis.user where id = #{id} </delete>
注意点
增删改需要提交事务!
万能Map
假设我们的实体类,或者数据库中的表,字段或者参数过多,可以考虑使用Map
int addUser2(Map<String,Object> map);
Map传递参数,直接在sql中取出key【paramterType=“map”】
对象传递参数,直接在sql中取对象的属性即可【paramterType=“Object”】
只有一个基本类型参数的情况下,可以直接在sql中取到!
多个参数用Map,或者用注解
模糊查询
模糊查询怎么写?
List userList = mapper.getUserLike(“%李%”);
配置解析
- 核心配置文件
mybatis-config.xml - MyBatis的配置文件包含了绘画深深影响Mybatis行为的设置和属性信息
configuration(配置)
properties(属性)
settings(设置)
typeAliases(类型别名)
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境配置)
environment(环境变量)
transactionManager(事务管理器)
dataSource(数据源)
databaseIdProvider(数据库厂商标识)
mappers(映射器)
## 环境变量配置
MyBatis 可以配置成适应多种环境,**不过要记住:尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。**
Mybatis默认的事务管理器是JDBC,连接池是:POOLED
## 属性(properties)
我们可以通过properties属性来实现引用配置文件
这些属性都是可外部配置且可动态替换的,既可以在典型的Java属性文件中配置,也可以通过propertis元素的子元素来传递。【db.properties】
编写一个配置文件
driver = com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf8
username=root
password=201103
在核心配置文件中引入(可以直接引入外部文件、可以在其中增加一些属性配置、如果两个文件有相同字段,优先使用外部配置文件)
[<properties resource="db.properties"/>]()
## 类别名(typeAliases)
类型别名是为java类型设置一个短的名字。它之和xml有关,存在意义仅在于减少类完全限定名的冗余
```
也可以指定一个包名,Mybatis会在包名下面搜索需要的javabean,比如:扫描实体类的包,它的默认别名就为这个类的类名,首字母小写!
<typeAliases>
<package name="com.kuang.pojo"/>
</typeAliases>
在实体类比较少的时候,使用第一种方式,如果实体类十分多建议使用第二种!第一种可以DIY(自定义),第二种则不行,如果非要改,需要在实体类上添加注解@Alias()
设置(settings)
这是mybatis中极其重要的调整设置,它们会改变mybatis的运行时行为。
映射器(mappers)
MapperRegistry:注册绑定我们的Mapper文件
<mappers>
<mapper resource="com/kuang/dao/UserMapper.xml"> </mapper>
</mappers>
生命周期和作用域
SqlSessionFactoryBuilder:
一旦创建SqlSessionFactory,就不再需要它了
SqlSessionFactory
可以想象为:数据库连接池
SqlSessionFactory一旦被创建那就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例
因此SqlSessionFactory的最佳作用域是应用作用域
最简单的就是使用单例模式或者静态单例模式
SqlSession
连接到连接池的一个请求
SqlSession的实例不是线程安全的,因此是不能被共享的,所以它的最佳作用域是请求或方法作用域
用完之后需要赶紧关闭,否则资源被占用!
## 日志
### 日志工厂
如果一个数据库操作,出现了异常,我们需要排错。日志就是最好的帮手
曾经:sout debug
现在:日志工厂!
在Mybatis中具体使用哪个日志实现,在设置中设定
STDOUT_LOGGING
在mybatis核心配置文件中的设置我们的配置
```
Log4j
1、先导入Log4j
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
log4j.properties配置文件
#############
# 输出到控制台
#############
# log4j.rootLogger日志输出类别和级别:只输出不低于该级别的日志信息DEBUG < INFO < WARN < ERROR < FATAL
# WARN:日志级别 CONSOLE:输出位置自己定义的一个名字 logfile:输出位置自己定义的一个名字
log4j.rootLogger=WARN,CONSOLE,logfile,DEBUG
# 配置CONSOLE输出到控制台
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
# 配置CONSOLE设置为自定义布局模式
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
# 配置CONSOLE日志的输出格式 [frame] 2019-08-22 22:52:12,000 %r耗费毫秒数 %p日志的优先级 %t线程名 %C所属类名通常为全类名 %L代码中的行号 %x线程相关联的NDC %m日志 %n换行
log4j.appender.CONSOLE.layout.ConversionPattern=[frame] %d{yyyy-MM-dd HH:mm:ss,SSS} - %-4r %-5p [%t] %C:%L %x - %m%n
################
# 输出到日志文件中
################
# 配置logfile输出到文件中 文件大小到达指定尺寸的时候产生新的日志文件
log4j.appender.logfile=org.apache.log4j.RollingFileAppender
# 保存编码格式
log4j.appender.logfile.Encoding=UTF-8
# 输出文件位置此为项目根目录下的logs文件夹中
log4j.appender.logfile.File=logs/root.log
# 后缀可以是KB,MB,GB达到该大小后创建新的日志文件
log4j.appender.logfile.MaxFileSize=10MB
# 设置滚定文件的最大值3 指可以产生root.log.1、root.log.2、root.log.3和root.log四个日志文件
log4j.appender.logfile.MaxBackupIndex=3
# 配置logfile为自定义布局模式
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %F %p %m%n
##########################
# 对不同的类输出不同的日志文件
##########################
# club.bagedate包下的日志单独输出
log4j.logger.club.bagedate=DEBUG,bagedate
# 设置为false该日志信息就不会加入到rootLogger中了
log4j.additivity.club.bagedate=false
# 下面就和上面配置一样了
log4j.appender.bagedate=org.apache.log4j.RollingFileAppender
log4j.appender.bagedate.Encoding=UTF-8
log4j.appender.bagedate.File=logs/bagedate.log
log4j.appender.bagedate.MaxFileSize=10MB
log4j.appender.bagedate.MaxBackupIndex=3
log4j.appender.bagedate.layout=org.apache.log4j.PatternLayout
log4j.appender.bagedate.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %F %p %m%n
配置log4j为日志的实现
<settings>
<setting name="logImpl" value=""/>
</settings>
分页
使用mybatis实现分页
接口
//分页
List<User> getUserByLimit(Map<String,Integer> map);
Mapper.xml
<select id="getUserByLimit" parameterType="map" resultType="User">
select * from mybatis.user limit #{startIndex},#{pageSize}
</select>
测试
@Test
public void getUserByLimit(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("startIndex",0);
map.put("pageSize",4);
List<User> userList = mapper.getUserByLimit(map);
for (User user: userList) {
System.out.println(user);
}
sqlSession.close();
}
使用注解开发
-
注解就直接在接口上实现
@Select("select * from user") List<User> getUsers();
-
需要在核心配置文件中绑定接口
<mappers> <mapper class="com.kuang.dao.UserMapper"></mapper> </mappers>
-
测试
本质:反射机制实现
底层:动态代理
Mybatis详细的执行流程
Resources获取加载全局配置文件-》实例化SqlSessionFactoryBuilder构造器-》解析配置文件流XMLConfigBuilder-》Configuration所有的配置信息-》实例化SqlSessionFactory-》transaction事务管理-》创建executor执行器-》创建SqlSession-》实现CRUD
CRUD
我们可以在测试类中实现自动提交事务
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession(true);
}
接口
package com.kuang.dao;
import com.kuang.pojo.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
public interface UserMapper {
@Select("select * from user")
List<User> getUsers();
// 方法存在多个参数,所有的参数前面必须加上@Param("id")注解
@Select("select * from user where id = #{id}")
User getUserById(@Param("id") int id);
@Insert("insert into user(id, name, pwd) values(#{id}, #{name}, #{pwd})")
int addUser(User user);
@Update("update user set name = #{name}, pwd = #{pwd} where id = #{id}")
int updateUser(User user);
@Delete("delete from user where id = #{id}")
int deleteUser(@Param("id") int id);
}
关于@Param()注解
- 基本类型的参数或者String类型,需要加上
- 引用类型不需要加
- 如果只有一个基本类型的话,可以忽略,但是建议都加上
- 我们在SQL中引用的就是我们@Param中设定的属性名
多对一处理
按照查询嵌套处理
<select id="getStudent" resultMap="StudentTeacher">
select * from mybatis.student
</select>
<resultMap id="StudentTeacher" type="Student">
<result property="id" column="id"></result>
<result property="name" column="name"></result>
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher"></association>
</resultMap>
<select id="getTeacher" resultType="Teacher">
select * from mybatis.teacher where id = #{id}
</select>
按照结果嵌套处理
<select id="getStudent2" resultMap="StudentTeacher2">
select s.id sid, s.name sname,t.name tname from mybatis.teacher t,mybatis.student s where s.tid = t.id
</select>
<resultMap id="StudentTeacher2" type="Student">
<result property="id" column="sid"></result>
<result property="name" column="sname"></result>
<association property="teacher" javaType="Teacher">
<result property="id" column="id"></result>
<result property="name" column="tname"></result>
</association>
</resultMap>
一对多处理
比如:一个老师有多个学生,对于老师而言就是一对多的关系
Teacher实体类
private int id;
private String name;
private List<Student> students;
Student实体类
private int id;
private String name;
//学生需要关联一个老师!
private int tid;
按照结果嵌套处理
<select id="getTeacher" resultMap="TeacherStudent">
select s.id sid, s.name sname, t.name tname from mybatis.teacher t, mybatis.student s where s.id = t.id and t.id = #{tid}
</select>
<resultMap id="TeacherStudent" type="Teacher">
<result property="id" column="tid"></result>
<result property="name" column="tname"></result>
<collection property="students" ofType="Student">
<result property="id" column="sid"></result>
<result property="name" column="sname"></result>
<result property="tid" column="tid"></result>
</collection>
</resultMap>
小结
- 关联-association [多对一]
- 集合-collection[一对多]
- javaType & ofType
- javaType用来指定实体类中属性的类型
- ofType 用来指定映射到List或者集合中的pojo类型,范型中的约束类型!
面试高频
- Mysql引擎、
- InnoDB底层原理
- 索引
- 索引优化!
动态SQL
什么是动态SQL:动态SQL就是根据不同的条件生成不同的SQL语句
搭建环境
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
创建一个基础工程
-
导包
-
编写配置文件
package com.kuang.pojo; import java.util.Date; public class Blog { private int id; private String title; private String author; private Date createTime; private int views; public Blog() { } public Blog(int id, String title, String author, Date createTime, int views) { this.id = id; this.title = title; this.author = author; this.createTime = createTime; this.views = views; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public int getViews() { return views; } public void setViews(int views) { this.views = views; } @Override public String toString() { return "Blog{" + "id=" + id + ", title='" + title + '\'' + ", author='" + author + '\'' + ", createTime=" + createTime + ", views=" + views + '}'; } }
-
编写实体类
-
编写实体类对应的Mapper接口和对应的.xml文件
缓存
什么是缓存?
- 存在内存中的临时数据
- 将用户经常访问的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库数据文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题
为什么使用缓存
- 减少和数据库的交互次数,减少系统开销,提高系统效率
什么样的数据能使用缓存?
- 经常查询并且不经常改变的数据。
Mybatis缓存
Mybatis包含一个非常强大的查询缓存特性,他可以非常方便地定制和配置缓存。缓存可以极大的提升查询效率
Mybatis系统中默认定义了两级缓存:一级缓存和二级缓存
- 默认情况下,只有一级缓存开启(SqlSession级别的缓存,也称为本地缓存)
- 二级缓存需要手动开启和配置,他是基于namespace级别的缓存
- 为了提高扩展性,MyBatis定义了缓存接口Cache,我们可以通过实现Cache接口来自定义二级缓存
一级缓存
一级缓存也叫本地缓存:SqlSession
- 与数据库同一次会话期间查询到的数据会放在本地缓存中。
- 以后如果需要获取相同的数据,直接从缓存中拿,没必须再去查询数据库。
测试步骤:
1、开启日志
2、测试在一个Session中查询两次相同记录
3、查看日志输出
缓存失效的情况:
- 查询不同的东西
- 增删改操作,可能会改变原来的数据,所以必定会刷新缓存
- 查询不同的Mapper.xml
- 手动清理缓存!
小结:一级缓存默认是开启的,只在一次SqlSession中有效,也就是拿到连接到关闭连接这个区间段
二级缓存
二级缓存也称全局缓存,因为一级缓存的作用域太低了,所以诞生了二级缓存
基于namespace级别的缓存,一个名称空间,对应一个二级缓存
工作机制
- 一个会话查询一条数据,这个数据就会放在当前会话的一级缓存
- 如果当前会话关闭了,这个会话对应的一级缓存就没了;但是我们想要的是,会话关闭了,一级缓存中的数据被保存到二级缓存中。
- 新的会话查询信息,就可以从二级缓存中获取内容
- 不同的mapper查出的数据会放在自己对应的缓存(map)中
步骤
- 开启全局缓存
关系型数据库数据文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题
为什么使用缓存
- 减少和数据库的交互次数,减少系统开销,提高系统效率
什么样的数据能使用缓存?
- 经常查询并且不经常改变的数据。
Mybatis缓存
Mybatis包含一个非常强大的查询缓存特性,他可以非常方便地定制和配置缓存。缓存可以极大的提升查询效率
Mybatis系统中默认定义了两级缓存:一级缓存和二级缓存
- 默认情况下,只有一级缓存开启(SqlSession级别的缓存,也称为本地缓存)
- 二级缓存需要手动开启和配置,他是基于namespace级别的缓存
- 为了提高扩展性,MyBatis定义了缓存接口Cache,我们可以通过实现Cache接口来自定义二级缓存
一级缓存
一级缓存也叫本地缓存:SqlSession
- 与数据库同一次会话期间查询到的数据会放在本地缓存中。
- 以后如果需要获取相同的数据,直接从缓存中拿,没必须再去查询数据库。
测试步骤:
1、开启日志
2、测试在一个Session中查询两次相同记录
3、查看日志输出
缓存失效的情况:
- 查询不同的东西
- 增删改操作,可能会改变原来的数据,所以必定会刷新缓存
- 查询不同的Mapper.xml
- 手动清理缓存!
小结:一级缓存默认是开启的,只在一次SqlSession中有效,也就是拿到连接到关闭连接这个区间段
二级缓存
二级缓存也称全局缓存,因为一级缓存的作用域太低了,所以诞生了二级缓存
基于namespace级别的缓存,一个名称空间,对应一个二级缓存
工作机制
- 一个会话查询一条数据,这个数据就会放在当前会话的一级缓存
- 如果当前会话关闭了,这个会话对应的一级缓存就没了;但是我们想要的是,会话关闭了,一级缓存中的数据被保存到二级缓存中。
- 新的会话查询信息,就可以从二级缓存中获取内容
- 不同的mapper查出的数据会放在自己对应的缓存(map)中
步骤
- 开启全局缓存