从零再学mybatis
直观的来说mybatis有以下特点
- 使用灵活,sql高度可定制
- 性能优化易操作
- 入门门槛低,只需要掌握sql语法即可
- 实现与接口相分离
- orm 框架(半自动,需要手动编写sql)
mybatis如此优秀,易上手,性能可以有效优化,使得其成为非常流行的数据库后端框架之一.
现在针对mybatis提出以下问题:
- mybatis 如何将.xml 文件mapper接口绑定到一起产生对象的?
- mybatis的缓存是如何管理的
mybatis 基本环境搭建:
需要的文件
- 数据库脚本
- pojo 类 User
- UserMapper 接口,UserMapper.xml
- mybatis.jar 包
- mybatis-config.xml
- db.properties
具体步骤
- sql 脚本
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) CHARACTER SET utf8mb4 DEFAULT NULL,
`password` varchar(32) CHARACTER SET utf8mb4 DEFAULT NULL,
`sex` varchar(10) CHARACTER SET utf8mb4 DEFAULT NULL,
`description` varchar(255) CHARACTER SET utf8mb4 DEFAULT '',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;
- User 类
public class User {
private int id;
private String name;
private String sex;
private String description;
private String password;
public User() {
}
public User(String name, String sex, String description) {
this.name = name;
this.sex = sex;
this.description = description;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", sex='" + sex + '\'' +
", description='" + description + '\'' +
'}';
}
... 省略getter/setter
}
- UserMapper.java 接口 以及UserMapper.xml 文件
public interface UserMapper {
void insert(User user);
User getById(int id);
}
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="top.forethought.framework.mybatis.dao.UserMapper">
<resultMap type="top.forethought.framework.jdbctemplate.User" id="usermap">
<id column="id" property="id"/>
<result column="name" property="name"/>
<result column="password" property="password"/>
<result column="sex" property="sex"/>
<result column="description" property="description"/>
</resultMap>
<select id="getById" parameterType="int" resultMap="usermap">
select * from user where id=#{id}
</select>
<insert id="insert">
insert into user ( name,password, sex,description) values (
#{name}, #{password},#{sex}, #{description}
)
</insert>
</mapper>
- pom.xml 依赖
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}3.2.8</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis.spring.version}</version>
</dependency>
- 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>
<properties resource="top/forethought/framework/configs/db.properties">
</properties>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${jdbcUrl}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="top/forethought/framework/mybatis/mapper/UserMapper.xml"/>
</mappers>
</configuration>
- db.properties ,配置具体的数据库参数,供xml文件中引用
username=noneroot
password=18142513872
jdbcUrl=jdbc:mysql://localhost:3306/test_index?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT
driver=com.mysql.jdbc.Driver
- 测试类 TestMapper.java
public class TestMapper {
@Test
public void testMybatis() throws IOException {
String resource = "top/forethought/framework/configs/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory =
new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession=sqlSessionFactory.openSession();
UserMapper mapper= sqlSession.getMapper(UserMapper.class);
User user=new User();
user.setName("123");
user.setSex("男");
user.setDescription("这是人物描述"+System.currentTimeMillis());
mapper.insert(user);
System.out.println("查询来自数据库:"+mapper.getAll().toString());
sqlSession.commit();// 如果不commit 是不能提交事务到数据库的
sqlSession.close();
}
}
- 测试效果
mybatis如何产生实实在在的mapper对象
先看最终结果
显然最终得到的是实现了UserMapper 中接口方法的代理类
再看debug 过程
以下截图主要是为了记录执行流程
MapperRegistry:看名字可以知道这是mapper注册器,所有mapper接口与相应实现xml文件绑定成功成功后会保存一条记录到knownMappers 之中
knownNappers ,是一个Map ,以接口名为key(比如这里是UsernMapper),
MapperProxyFactory 为val
即:记录了接口与mapper代理工厂之间的映射关系
MapperProxyFactory: 有一个Map 来保存 接口中的方法到mapper.xml 中的具体实现(MapperMethod)的映射关系
MapperMethod:
大体流程如下:
MapperRegistry 的getMapper 方法中,调用了MapperProxyFactory的newInstance 方法获取到
根据接口生成的代理对象
生成的代理对象应该使用的是jdk的动态代理
调用mapper.insert() 方法时,可以发现
结论
- mapper 与xml的绑定,使用了工厂模式产生代理对象(实现了接口)
- 采用了jdk动态代理(InvocationHandler)
- 使用反射创建代理对象
- 主要参与的类有MapperRegistry(根据接口找代理MapperProxyFactory),MapperProxyFactory(造代理对象)
mybatis 如何配置或者是管理缓存
可以查看打印输出的sql语句来判断是否使用了缓存
- 配置sql输出
在mybatis-config.xml 的中添加以下内容(注意位置,会有提示,按照提示处理标签顺序即可,这是由dtd来约束的)
<settings>
<!-- 打印查询语句 -->
<setting name="logImpl" value="STDOUT_LOGGING" />
</settings>
- 修改测试类代码
public class TestMapper {
@Test
public void testMybatis() throws IOException {
String resource = "top/forethought/framework/configs/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory =
new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession=sqlSessionFactory.openSession();
UserMapper mapper= sqlSession.getMapper(UserMapper.class);
// User user=new User();
// user.setName("123");
// user.setSex("男");
// user.setDescription("这是人物描述"+System.currentTimeMillis());
// mapper.insert(user);
// 连续在相同条件下查询两次数据库,发现输出的sql只有一句
System.out.println("查询来自数据库:"+mapper.getAll().toString());
System.out.println("查询来自数据库:"+mapper.getAll().toString());
// sqlSession.commit();// 如果不commit 是不能提交事务到数据库的
sqlSession.close();
}
}
输出:
尝试关闭mybatis缓存
mybatis-config.xml 的settings添加
<setting name="cacheEnabled " value="false"/>
测试效果:
发现还是只是输出了一句,难道是打开方式不对!!!
cacheEnabled:是缓存的全局配置,如果关闭,那么其他有关缓存的配置都将是无效的
Globally enables or disables any caches configured in any mapper under this configuration.
参数配置错了,应该配置 localCacheScope属性,可以配置cache范围是SESSION还是STATEMENT
SESSION:表示同一个session,所有的查询都会被缓存,那么相同的查询执行第二遍,那么就是去缓存取数据了,而不是再次去数据库查询
STATEMENT:表示每一个语句都是去数据库查询
MyBatis uses local cache to prevent circular references and speed up repeated nested queries. By default (SESSION) all queries executed during a session are cached. If localCacheScope=STATEMENT local session will be used just for statement execution, no data will be shared between two different calls to the same SqlSession
<setting name="localCacheScope" value="STATEMENT"/>
效果:
疑问:
可能对SESSION会有疑问了,如果是设置为SESSION,同一个session内指向两次相同查询的之间再执行一条插入语句,那么第二次查询还是会从缓存取吗?
测试结果发现,这样是执行了两次数据库查询
更多的settings 相关配置,传送
其他小问题:
Cause: java.sql.SQLException: Incorrect string value: ‘\xE7\x94\xB7’ for column ‘sex’ at row 1
原因:数据库字符编码问题