MyBatis源码解析系列参考:http://www.mybatis.org/mybatis-3/zh/index.html和源码调试,加上画图理解
首先在掌握一门技术前,先得知道它是是什么,怎么用。之后再掌握底层原理
1、使用传统JDBC编程:
public static void test() {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
// 加载数据库驱动
Class.forName("com.mysql.jdbc.Driver");
// 获取数据库连接
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/table_v200?characterEncoding=utf-8", "root", "1234");
//定义sql语句
String sql = "select * from user_weixin where id>? limit 5";
//使用preparedStatement预编译,防止sql注入
preparedStatement = connection.prepareStatement(sql);
//设置参数
preparedStatement.setInt(1, 2);
/**
* PreparedStatement prepareStatement(String var1, int var2, int var3)
* var1:sql语句
* var2:结果集类型:决定ResultSet对象是否可以滚动,是否对数据库中的修改敏感。
* var3:结果集并发性 决定Rs 是否可以修改数据库中的行。
*/
preparedStatement = connection.prepareStatement(sql);
// 执行sql,获取结果
resultSet = preparedStatement.executeQuery();
// 遍历游标解析结果集
while (resultSet.next()) {
System.out.println("id:" + resultSet.getString("id"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 释放资源
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
2、JDBC相关知识引申:
(1)sql注入:
所谓sql注入是将传入的参数包含有sql指令,或干扰sql指令执行的语句。or '1=1' 达到欺骗数据库。影响原意图执行的语句。
预编译是如何防止sql注入的?
程序在操作数据库之前,SQL语句已经被数据库分析,编译和优化,执行计划也会缓存下来并允许数据库以参数化的形式进行查询,
PreprareStatement收到传入的参数如or '1=1',只会将其当成参数的形式进来处理而不会作为一个SQL指令。
(2)结果集游标:
ResultSet对外部修改数据是否敏感:例如我们在执行select id,name ,age from user where age>32 limit 10时,将从数据库查询到的结果缓存到JVM中,正在遍历取数据时,这时候数据库的记录发生了更新。更新的数据,ResultSet是否可见。
游标遍历:支持向前、向后、最后一条,第一条。随机等都是在取数据时的api操作
ResultSet.TYPE_FORWARD_ONLY(默认)
仅仅支持向前forward
ResultSet.TYPE_SCROLL_INSENSITIVE
支持backforward,random,last,first操作,对外部数据修改不可见。其实也比较好理解。当我们将数据库符合条件的完整数据查询缓存到ResultSet中时,对结果集遍历等相关操作,只是基于内存中数据操作而已。跟数据库无关。所以数据库的值更新它是不知道的。
ResultSet.TYPE_SCROLL_SENSITIVE
支持backforward,random,last,first操作。对外部数据修改是可见。这里与TYPE_SCROLL_INSENSITIVE不同的是,select id,name ,age from user where age>32 limit 10 sql语句用TYPE_SCROLL_SENSITIVE的Statement来执行,会转化
select id from user where age>32 limit 10的结果先缓存起来。而真正在取数据的时候再通过select id from user where id=?
去数据库实时查询数据。所以对数据库的修改是可见的(只是修改,添加还是不可见。因为添加的id,第一次并未缓存起来)。
(3)批处理:
可以向数据库发送多条不同的SQL语句。
String sql1 = "insert into user_weixin(id,openid) values(?,?)";
preparedStatement = connection.prepareStatement(sql);
for(int i=1;i<1000;i++){
preparedStatement.setInt(1, i);
preparedStatement.setString(2, "openid" + i);
preparedStatement.addBatch();
if(i%100==0){
preparedStatement.executeBatch();
preparedStatement.clearBatch();
}
}
preparedStatement.executeBatch();
JDBC小结:
- 数据库连接频繁创建、释放频繁造成系统资源浪费如果使用数据库连接池可解决此问题。
- Sql语句在代码中硬编码
- 对结果集解析存在硬编码(查询列名),需要手动将结果集映射到实体中(取出每列的值,set到实体)。
3、MyBatis
MyBatis再神奇也就是对JDBC编程的封装,通过用 XML 或注解来配置和映射实体。 避免了 JDBC 代码和手动设置参数以及获取结果集。
使用MyBatis
(1)、引入依赖,在启动配置文件中配置数据库连接信息
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.3</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.30</version>
</dependency>
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=root
(2)、新建MyBatis配置文件:mybatis-configuration.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="jdbc.properties">
</properties>
<!-- 可以配置多个运行环境,但是每个 SqlSessionFactory 实例只能选择一个运行环境 一、development:开发模式 二、work:工作模式 -->
<environments default="development">
<!--id属性必须和上面的default一样 -->
<environment id="development">
<transactionManager type="JDBC" />
<!--dataSource 元素使用标准的 JDBC 数据源接口来配置 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>
<mapper resource="com/ys/mapper/userMapper.xml"/>
</mappers>
</configuration>
(3)配置映射器(接口和xml映射文件)
public interface UserMapper {
User selectUser();
}
<mapper namespace="org.apache.test.UserMapper">
<select id="selectUser" resultType="org.apache.test.User">
select name from user where id = #{id}
</select>
</mapper>
(4)使用MyBatis查询数据库,并将结果集映射到实体中
public static void main(String[] args) throws Exception {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory =
new SqlSessionFactoryBuilder().build(inputStream);
//通过sqlSessionFactory获取SqlSession
SqlSession session = sqlSessionFactory.openSession() {
//方式一:
UserMapper mapper = session.getMapper(UserMapper.class);
User user1 = mapper.selectBlog("1");
//方式二:
User user2 = session.selectOne(
"test.UserMapper.selectBlog", 1);
}
PS:后面就从源码分析上面的代码是如何对JDBC进行封装的