不说废话,直接开始
分析jdbc操作问题
思考
jdbc已经能够完成数据库的操作,已经能完成增删该查的操作,为什么改需要 MyBatis 呢?
原因
jdbc操作存在一些问题,哪些问题?通过 jdbc 代码分析
public static void main(String[] args) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
// 加载数据库驱动
Class.forName("com.mysql.jdbc.Driver");
// 通过驱动管理类获取数据库链接
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8", "root", "root");
// 定义sql语句?表示占位符
String sql = "select * from user where username = ?";
// 获取预处理statement
preparedStatement = connection.prepareStatement(sql);
// 设置参数,第⼀个参数为sql语句中参数的序号(从1开始),第⼆个参数为设置的参数值
preparedStatement.setString(1, "tom");
// 向数据库发出sql执⾏查询,查询出结果集
resultSet = preparedStatement.executeQuery();
// 遍历查询结果集
while (resultSet.next()) {
int id = resultSet.getInt("id");
String username = resultSet.getString("username");
// 封装User
user.setId(id);
user.setUsername(username);
}
System.out.println(user);
}
} 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();
}
}
}
画图分析
问题总结
- 数据库的连接创建、释放频繁造成系统资源浪费,从而影响系统性能
- sql语句在代码中硬编码,造成代码不易维护,实际应用中sql变换的可能较大,sql变动需要改变java代码
- 使用prepared Statement向占有位符号传参存在硬编码,因为sql语句的where条件不一定,可能多也可能少,修改sql还要修改代码,系统不易维护
- 对结果集解析存在硬编码(查询列名),sql变化导致解析代码变化,系统不易维护,如果能将数据库的库记录封装成pojo对象解析比较方便
问题解决
- 使用数据库连接池初始化连接资源
- 将sql语句抽取到xml配置文件中
- 使用反射、内省等底层技术,将自动实现与表进行属性与字段的自动映射
自定义持久层框架
设计思路
使用端(项目):
- 引入自定义持久层框架的jar包
- 使用配置文件提供两部分配置信息
- sqlMapConfig.xml:数据库配置信息、mapper.xml的全路径
- mapper.xml:sql配置信息:sql语句、参数类型、返回值类型
自定义持久层框架本身(工程):本质就是对JDBC代码进行封装
-
加载配置文件:根据配置文件的路径,加载配置文件成字节流,存储在内存中
创建类:Resources 方法:InputSteam getResourceAsSteam(String path)
-
创建两个javaBean(容器对象):存放的就是对配置文件解析出来的内容
Configuration(核心配置类):存放sqlMapConfig.xml解析出来的内容
MappedStatement(映射配置类):存放mapper.xml解析出来的内容
-
解析配置文件:dom4j
创建类:SqlSessionFactoryBuilder 方法:build(InputSteam in)
(1) 使用dom4j解析配置文件,将解析出来的内容封装到容器对象中
(2) 创建SqlSessionFactory对象:生产sqlSession(会话对象)--- 工厂模式
-
创建SqlSessionFactory接口及实现类DefaultSqlSessionFactory
openSession( ):生产sqlSession
-
创建SqlSession接口及实现类DefaultSession
定义对数据库的crud操作:selectList( )、selectOne( )、update( )、delete( )
-
创建Executor接口及实现类SimpleExecutor实现类
query(Configuration, MappedStatement, Object... params):执行的就是JDBC代码
图解分析
代码实现
创建Modules:IPersistence(自定义持久层框架)和 IPersistence_test(用户端)
代码实现中有详细注释!!
使用端
IPersistence_test
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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.zx</groupId>
<artifactId>IPersistence_test</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.encoding>UTF-8</maven.compiler.encoding>
<java.version>1.8</java.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<!-- 引入自定义持久层框架依赖 -->
<dependencies>
<dependency>
<groupId>com.zx</groupId>
<artifactId>IPersistence</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
</project>
sqlMapConfig.xml
数据库配置信息、mapper.xml的全路径
<configuration>
<!-- 数据库配置信息 -->
<dataSource>
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql:///zx_mybatis"></property>
<property name="" value="root"></property>
<property name="" value="root"></property>
</dataSource>
<!-- 存放mapper.xml的全路径 -->
<mapper resource="UserMapper.xml"></mapper>
</configuration>
UserMapper.xml
sql配置信息:sql语句、参数类型、返回值类型
<mapper namespace="user">
<!-- sql的唯一标识:namespace.id来组成的 -->
<select id="selectList" resultType="com.zx.pojo.User">
select * from user
</select>
<select id="selectOne" resultType="com.zx.pojo.Use" paramterType="com.zx.pojo.Use">
select * from user where id = #{id} and username = #{username}
</select>
</mapper>
User
package com.zx.pojo;
import java.io.Serializable;
public class User implements Serializable {
private Integer id;
private String username;
// getter... setter...
}
IPersistenceTest
package com.zx.test;
import com.zx.io.Resources;
import com.zx.pojo.User;
import com.zx.sqlSession.SqlSession;
import com.zx.sqlSession.SqlSessionFactory;
import com.zx.sqlSession.SqlSessionFactoryBuilder;
import org.junit.Test;
import java.io.InputStream;
import java.util.List;
public class IPersistenceTest {
@Test
public void test() throws Exception {
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSqlSession();
// 调用
List<User> list = sqlSession.selectList("user.selectList");
for (User user1 : list) {
System.out.println(user1);
}
}
}
自定义持久层框架
IPersistence
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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.zx</groupId>
<artifactId>IPersistence</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.encoding>UTF-8</maven.compiler.encoding>
<java.version>1.8</java.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.17</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
</dependency>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
<version>1.1.6</version>
</dependency>
</dependencies>
</project>
Configuration
package com.zx.pojo;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
/**
* Configuration(核心配置类):存放sqlMapConfig.xml解析出来的内容
* Configuration 即包含了数据库的配置信息:dataSource
* 也包含了sql的配置信息:mappedStatementMap
*/
public class Configuration {
/**
* 存放数据源配置
*/
private DataSource dataSource;
/**
* key:statementId
* value:封装好的 MappedStatement 对象
*/
Map<String, MappedStatement> mappedStatementMap = new HashMap<>();
// getter... setter...
}
MappedStatement
package com.zx.pojo;
/**
* MappedStatement(映射配置类):存放mapper.xml解析出来的内容
*/
public class MappedStatement {
/**
* id标识
*/
private String id;
/**
* 返回值类型
*/
private String resultType;
/**
* 参数值类型
*/
private String parameterType;
/**
* sql语句
*/
private String sql;
// getter... setter...
}
Resources
package com.zx.io;
import java.io.InputStream;
public class Resources {
/**
* 根据配置文件的路径,将配置文件加载成字节输入流,存储在内存中
* @param path:使用端传过来的配置文件的路径
* @return resourceAsStream:字节输入流
*/
public static InputStream getResourceAsStream(String path) {
// 获取类加载器
InputStream resourceAsStream = Resources.class.getClassLoader().getResourceAsStream(path);
return resourceAsStream;
}
}
SqlSessionFactoryBuilder
package com.zx.sqlSession;
import com.zx.config.XMLConfigBuilder;
import com.zx.pojo.Configuration;
import org.dom4j.DocumentException;
import java.beans.PropertyVetoException;
import java.io.InputStream;
/**
* 作用:
* 1.使用dom4j解析配置文件,将解析出来的内容封装到容器对象中
* 2.创建SqlSessionFactory对象,来生产sqlSession(会话对象)
*/
public class SqlSessionFactoryBuilder {
public SqlSessionFactory build(InputStream in) throws DocumentException, PropertyVetoException {
// 1.使用dom4j解析配置文件,将解析出来的内容封装到Configuration中
XMLConfigBuilder xmlConfigBuilder = new XMLConfigBuilder();
Configuration configuration = xmlConfigBuilder.parseConfig(in);
// 2.创建sqlSessionFactory对象:工厂类:生产sqlSession:会话对象
DefaultSqlSessionFactory defaultSqlSessionFactory = new DefaultSqlSessionFactory(configuration);
return defaultSqlSessionFactory;
}
}
XMLConfigBuilder
package com.zx.config;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.zx.io.Resources;
import com.zx.pojo.Configuration;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;
public class XMLConfigBuilder {
private Configuration configuration;
public XMLConfigBuilder() {
this.configuration = new Configuration();
}
/**
* 该方法就是使用dom4j对配置文件解析,封装Configuration
* @param inputStream
* @return
*/
public Configuration parseConfig(InputStream inputStream) throws DocumentException, PropertyVetoException {
/*
* 对 sqlMapConfig.xml 进行解析,封装Configuration
*/
Document document = new SAXReader().read(inputStream);
// 拿到sqlMapConfig.xml里的<configuration>
Element rootElement = document.getRootElement();
// 查找configuration里面的元素,"//xxx"-表示xxx在配置文件的任意位置都能够查找到
List<Element> list = rootElement.selectNodes("//property");
Properties properties = new Properties();
for (Element element : list) {
// 获取property标签里的 name 的值
String name = element.attributeValue("name");
// 获取property标签里的 value 的值
String value = element.attributeValue("value");
// name 和 value 的值都封装到 properties 里
properties.setProperty(name, value);
}
// 使用c3p0连接池,创建连接池对象,将他们封装到configuration这个对象中
ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
comboPooledDataSource.setUser(properties.getProperty("username"));
comboPooledDataSource.setPassword(properties.getProperty("password"));
configuration.setDataSource(comboPooledDataSource);
/*
* 对 mapper.xml 进行解析,封装Configuration
* 拿到路径 -- 字节输入流 -- dom4j进行解析
*/
List<Element> mapList = rootElement.selectNodes("//mapper");
// 每一个element就是对应的sqlMapConfig.xml里的一个<mapper>标签
// <mapper resource="UserMapper.xml"></mapper>
for (Element element : mapList) {
// 拿到路径
String mapperPath = element.attributeValue("resource");
// 获取字节输入流
InputStream resourceAsStream = Resources.getResourceAsStream(mapperPath);
// dom4j进行解析
XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
xmlMapperBuilder.parse(resourceAsStream);
}
return configuration;
}
}
XMLMapperBuilder
package com.zx.config;
import com.zx.pojo.Configuration;
import com.zx.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.InputStream;
import java.util.List;
public class XMLMapperBuilder {
private Configuration configuration;
public XMLMapperBuilder(Configuration configuration) {
this.configuration = configuration;
}
public void parse(InputStream inputStream) throws DocumentException {
Document document = new SAXReader().read(inputStream);
Element rootElement = document.getRootElement();
String namespace = rootElement.attributeValue("namespace");
List<Element> list = rootElement.selectNodes("//select");
// element对应的就是mapper.xml里的select语句标签
for (Element element : list) {
// 获取每个标签的id,resultType,parameterType,sql语句
String id = element.attributeValue("id");
String resultType = element.attributeValue("resultType");
String parameterType = element.attributeValue("parameterType");
String sqlText = element.getTextTrim();
// 封装到MappedStatement实体类中
MappedStatement mappedStatement = new MappedStatement();
mappedStatement.setId(id);
mappedStatement.setResultType(resultType);
mappedStatement.setParameterType(parameterType);
mappedStatement.setSql(sqlText);
// sql的唯一标识:statement namespace.id
String key = namespace +"."+ id;
configuration.getMappedStatementMap().put(key, mappedStatement);
}
}
}
SqlSessionFactory
package com.zx.sqlSession;
public interface SqlSessionFactory {
public SqlSession openSqlSession();
}
DefaultSqlSessionFactory
package com.zx.sqlSession;
import com.zx.pojo.Configuration;
public class DefaultSqlSessionFactory implements SqlSessionFactory {
private Configuration configuration;
public DefaultSqlSessionFactory(Configuration configuration) {
this.configuration = configuration;
}
@Override
public SqlSession openSqlSession() {
return new DefaultSqlSession(configuration);
}
}
SqlSession
package com.zx.sqlSession;
import java.util.List;
public interface SqlSession {
/**
* 查询所有
* @param statementId:对应 mapper.xml 里的sql唯一标识:namespace.id,Configuration中封装的key值
* @param params:按照条件查询 模糊查询
* @param <E>
* @return
*/
public <E> List<E> selectList(String statementId, Object... params) throws Exception;
/**
*
* @param statementId:对应 mapper.xml 里的sql唯一标识:namespace.id,Configuration中封装的key值
* @param params:按照条件查询
* @param <T>
* @return
*/
public <T> T selectOne(String statementId, Object... params) throws Exception;
}
DefaultSqlSession
package com.zx.sqlSession;
import com.zx.pojo.Configuration;
import com.zx.pojo.MappedStatement;
import java.util.List;
public class DefaultSqlSession implements SqlSession {
private Configuration configuration;
public DefaultSqlSession(Configuration configuration) {
this.configuration = configuration;
}
@Override
public <E> List<E> selectList(String statementId, Object... params) throws Exception {
// 将要去完成对simpleExecutor里的query方法的调用
SimpleExecutor simpleExecutor = new SimpleExecutor();
MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
List<E> list = simpleExecutor.query(configuration, mappedStatement, params);
return list;
}
@Override
public <T> T selectOne(String statementId, Object... params) throws Exception {
List<Object> objects = selectList(statementId, params);
if (objects.size() == 1) {
return (T) objects.get(0);
}else {
throw new RuntimeException("查询结果为空或返回结果过多");
}
}
}
Executor
package com.zx.sqlSession;
import com.zx.pojo.Configuration;
import com.zx.pojo.MappedStatement;
import java.util.List;
public interface Executor {
public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception;
}
SimpleExecutor
package com.zx.sqlSession;
import com.zx.config.BoundSql;
import com.zx.pojo.Configuration;
import com.zx.pojo.MappedStatement;
import com.zx.utils.GenericTokenParser;
import com.zx.utils.ParameterMapping;
import com.zx.utils.ParameterMappingTokenHandler;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;
public class SimpleExecutor implements Executor {
@Override
public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
// 1.注册驱动,获取连接
Connection connection = configuration.getDataSource().getConnection();
// 2.获取sql语句 select * from user where id = #{id} and username = #{username}
// 转换sql语句 select * from user where id = ? and username = ?,转换过程中,还要对#{}里面的值进行解析存储
String sql = mappedStatement.getSql();
BoundSql boundSql = getBoundSql(sql);
// 3.获取预处理对象:preparedStatement
PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());
// 4.设置参数
// 获取参数的全路径
String parameterType = mappedStatement.getParameterType();
// 根据参数的全路径获取它的class对象
Class<?> parameterTypeClass = getClassType(parameterType);
List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
for (int i = 0; i < parameterMappingList.size(); i++) {
// 取出parameterMappingList里的每一个对象
ParameterMapping parameterMapping = parameterMappingList.get(i);
// 取出#{}里面的内容 id,username
String content = parameterMapping.getContent();
// 反射:通过content获取实体类的属性值
Field declaredField = parameterTypeClass.getDeclaredField(content);
// 设置暴力访问
declaredField.setAccessible(true);
// 设置参数
Object o = declaredField.get(params[0]);
preparedStatement.setObject(i+1, o);
}
// 5.执行sql
// 查询出来的结果封装在 resultSet 中
ResultSet resultSet = preparedStatement.executeQuery();
// 6.封装返回结果集
// 获取返回值类型
String resultType = mappedStatement.getResultType();
// 转为class对象(new PropertyDescriptor使用)
Class<?> resultTypeClass = getClassType(resultType);
// 用于存放封装好的o
ArrayList<Object> objects = new ArrayList<>();
while (resultSet.next()) {
// 获取resultTypeClass的具体实现,Object对象(writeMethod.invoke使用)
Object o = resultTypeClass.newInstance();
// 取出resultSet的元数据,元数据中包含了字段名
ResultSetMetaData metaData = resultSet.getMetaData();
// metaData.getColumnCount()列的个数,数据库里有两列,则小于等于2
for (int i = 1; i <= metaData.getColumnCount(); i++) {
// 字段名 metaData.getColumnName(i)要从1开始,所以定义为i=1开始遍历
String columnName = metaData.getColumnName(i);
// 字段的值
Object value = resultSet.getObject(columnName);
// 使用反射或者内省,根据数据库表和实体类的对应关系,完成封装
// PropertyDescriptor类会将resultTypeClass对象中的columnName属性生成读写方法
PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultTypeClass);
// 获取propertyDescriptor的写方法
Method writeMethod = propertyDescriptor.getWriteMethod();
// 把字段的值value封装到对象o中
writeMethod.invoke(o, value);
}
// 将封装好的o存进List集合中
objects.add(o);
}
return (List<E>) objects;
}
private Class<?> getClassType(String parameterType) throws ClassNotFoundException {
if (parameterType != null) {
Class<?> aClass = Class.forName(parameterType);
return aClass;
}
return null;
}
/**
* 完成对#{}的解析工作
* 1.将#{}使用?进行代替
* 2.解析出#{}里面的值进行存储
* @param sql
* @return
*/
private BoundSql getBoundSql(String sql) {
// 标记处理类:配置标记解析器来完成对占位符的解析处理工作
ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
// 标记解析器 openToken:开始标记,closeToken:结束标记,handler:标记处理器
GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
// parseSql就是解析后的sql语句
String parseSql = genericTokenParser.parse(sql);
// parameterMappings就是解析出来的#{}参数名称
List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();
BoundSql boundSql = new BoundSql(parseSql, parameterMappings);
return boundSql;
}
}
BoundSql
package com.zx.config;
import com.zx.utils.ParameterMapping;
import java.util.ArrayList;
import java.util.List;
public class BoundSql {
/**
* 解析过后的sql
*/
private String sqlText;
/**
* 解析出来的参数集合
*/
private List<ParameterMapping> parameterMappingList = new ArrayList<>();
public BoundSql(String sqlText, List<ParameterMapping> parameterMappingList) {
this.sqlText = sqlText;
this.parameterMappingList = parameterMappingList;
}
// getter... setter...
}
GenericTokenParser
(MyBatis源码中粘贴)
package com.zx.utils;
public class GenericTokenParser {
private final String openToken; //开始标记
private final String closeToken; //结束标记
private final TokenHandler handler; //标记处理器
public GenericTokenParser(String openToken, String closeToken, TokenHandler handler) {
this.openToken = openToken;
this.closeToken = closeToken;
this.handler = handler;
}
/**
* 解析${}和#{}
* @param text
* @return
* 该方法主要实现了配置文件、脚本等片段中占位符的解析、处理工作,并返回最终需要的数据。
* 其中,解析工作由该方法完成,处理工作是由处理器handler的handleToken()方法来实现
*/
public String parse(String text) {
// 验证参数问题,如果是null,就返回空字符串。
if (text == null || text.isEmpty()) {
return "";
}
// 下面继续验证是否包含开始标签,如果不包含,默认不是占位符,直接原样返回即可,否则继续执行。
int start = text.indexOf(openToken, 0);
if (start == -1) {
return text;
}
// 把text转成字符数组src,并且定义默认偏移量offset=0、存储最终需要返回字符串的变量builder,
// text变量中占位符对应的变量名expression。判断start是否大于-1(即text中是否存在openToken),如果存在就执行下面代码
char[] src = text.toCharArray();
int offset = 0;
final StringBuilder builder = new StringBuilder();
StringBuilder expression = null;
while (start > -1) {
// 判断如果开始标记前如果有转义字符,就不作为openToken进行处理,否则继续处理
if (start > 0 && src[start - 1] == '\\') {
builder.append(src, offset, start - offset - 1).append(openToken);
offset = start + openToken.length();
} else {
//重置expression变量,避免空指针或者老数据干扰。
if (expression == null) {
expression = new StringBuilder();
} else {
expression.setLength(0);
}
builder.append(src, offset, start - offset);
offset = start + openToken.length();
int end = text.indexOf(closeToken, offset);
while (end > -1) {////存在结束标记时
if (end > offset && src[end - 1] == '\\') {//如果结束标记前面有转义字符时
// this close token is escaped. remove the backslash and continue.
expression.append(src, offset, end - offset - 1).append(closeToken);
offset = end + closeToken.length();
end = text.indexOf(closeToken, offset);
} else {//不存在转义字符,即需要作为参数进行处理
expression.append(src, offset, end - offset);
offset = end + closeToken.length();
break;
}
}
if (end == -1) {
// close token was not found.
builder.append(src, start, src.length - start);
offset = src.length;
} else {
//首先根据参数的key(即expression)进行参数处理,返回?作为占位符
builder.append(handler.handleToken(expression.toString()));
offset = end + closeToken.length();
}
}
start = text.indexOf(openToken, offset);
}
if (offset < src.length) {
builder.append(src, offset, src.length - offset);
}
return builder.toString();
}
}
ParameterMapping
(MyBatis源码中粘贴)
package com.zx.utils;
public class ParameterMapping {
private String content;
public ParameterMapping(String content) {
this.content = content;
}
// getter... setter...
}
ParameterMappingTokenHandler
(MyBatis源码中粘贴)
package com.zx.utils;
import java.util.ArrayList;
import java.util.List;
public class ParameterMappingTokenHandler implements TokenHandler {
private List<ParameterMapping> parameterMappings = new ArrayList<ParameterMapping>();
// context是参数名称 #{id} #{username}
public String handleToken(String content) {
parameterMappings.add(buildParameterMapping(content));
return "?";
}
private ParameterMapping buildParameterMapping(String content) {
ParameterMapping parameterMapping = new ParameterMapping(content);
return parameterMapping;
}
// getter... setter...
}
TokenHandler
(MyBatis源码中粘贴)
package com.zx.utils;
public interface TokenHandler {
String handleToken(String content);
}
自定义持久层框架优化
问题
- Dao层使用自定义持久层框架,存在代码重复,整个操作的过程重复(加载配置文件、创建sqlSessionFactory、生产sqlSession)
- statementId存在硬编码
解决方案
使用代理模式生成Dao层的代理实现类
代码实现
SqlSession中新增
/**
* 为Dao接口生成动态代理
* @param mapperClass
* @param <T>
* @return
*/
public <T> T getMapper(Class<?> mapperClass);
DefaultSqlSession中新增
@Override
public <T> T getMapper(Class<?> mapperClass) {
// 使用JDK动态代理来为Dao接口生成动态代理对象,并返回
Object proxyInstance = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
/**
* 底层都是去执行JDBC代码
* 根据不同情况来调用selectList或者selectOne
* @param proxy:当前代理对象的引用
* @param method:当前被调用方法的引用
* @param args:传递的参数
* @return
* @throws Throwable
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// 准备参数 1:statementId:sql的唯一标识:namespace.id = 接口的全限定名.方法名
// 方法名 findAll
String methodName = method.getName();
// 全限定名 com.zx.pojo.User
String className = method.getDeclaringClass().getName();
String statementId = className + "." + methodName;
// 准备参数 2:params:就是args
// 获取被调用方法的返回值类型
Type genericReturnType = method.getGenericReturnType();
// 判断是否进行了范型类型参数化
if (genericReturnType instanceof ParameterizedType) {
return selectList(statementId, args);
}
return selectOne(statementId, args);
}
});
return (T) proxyInstance;
}
以上就是一个简单功能的MyBatis框架的自定义了