⾃定义持久层框架
# ⾃定义持久层框架
# 分析JDBC开发问题
下例是JDBC操作MySQL数据库的示例:
/**
* JDBC操作数据数据库的问题
*/
public class JDBCDemo {
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",
"123456");
// 定义sql语句 ?表示占位符
String sql = "select * from user where username = ?";
// 获取预处理 statement
preparedStatement = connection.prepareStatement(sql);
// 设置参数,第⼀个参数为sql语句中参数(?)的序号(从1开始),第⼆个参数为设置的参数值
preparedStatement.setString(1, "jack");
// 向数据库发出sql执⾏查询,查询出结果集
resultSet = preparedStatement.executeQuery();
// 遍历查询结果集
while (resultSet.next()) {
int id = resultSet.getInt("id");
String username = resultSet.getString("username");
// 封装User
User user = new 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();
}
}
}
}
}
原始JDBC开发存在的问题如下:
- 数据库连接创建、释放频繁造成系统资源浪费,从⽽影响系统性能。
- SQL语句硬编码,代码不易维护。实际应⽤中SQL变化可能较⼤,那么SQL变动需要改变Java代码。
- 使⽤preparedStatement中占有位符传参数存在硬编码,代码不易维护。因为SQL语句的Where条件通常会随着业务变动,可能多也可能少,那么修改SQL还要Java修改代码。
- 对返回的结果集解析处理存在硬编码,代码不易维护。通常我们需要处理查询的列名映射到实体对象,那么SQL的返回列发生变化就会导致解析代码也需要更改。
# 解决思路
- 数据库连接配置信息放到xml、properties中,使用数据库连接池初始化连接资源
- SQL语句抽取到xml配置文件中
- 使用反射、内省等技术,自动将实体与表进行属性与字段的自动映射
# 自定义框架设计
# 客户端/使用端
主要提供核心配置文件: 数据库配置信息,sql配置信息
- sqlMapConfig.xml : 存放数据源配置信息,引入mapper.xml
- Mapper.xml : SQL语句的配置文件信息,包括sql语句、参数类型、返回值类型等等
# 框架端
框架端本质上是对JDBC代码进行了封装
加载配置文件:
根据配置文件路径,加载配置文件
sqlMapConfig.xml
成字节流,将读取到的配置信息以javaBean(容器对象)的方式存储在内存中,方便操作。- Configuration: 存放数据库基本信息、Map<唯一标识,Mapper> 唯一标识:
namespace + "."+ id
- MappedStatement : SQL语句、Statement类型、输入参数Java类型、输出参数Java类型
- Configuration: 存放数据库基本信息、Map<唯一标识,Mapper> 唯一标识:
解析配置文件
使用dom4j技术解析。创建sqlSessionFactoryBuilder类,方法:sqlSessionFactory.build(InputSteam in):
- 使用dom4j解析配置文件,将解析出来的内容封装到Configuration和MappedStatement中
- 创建SqlSessionFactory对象,负责生产sqlSession会话。
创建SqlSessionFactory接口以及默认实现类DefaultSqlSessionFactory
- openSession(): 获取sqlSession接口的实现类实例对象
创建SqlSession接口及实现类DefaultSession:
主要封装crud方法,封装JDBC完成对数据库表的查询操作
- selectList(String statementId, Object param): 查询所有
- selectOne(String statementId,Object param): 查询单个
- ......
创建Executor接口以及实现类SimpleExecutor实现类
- query(Configuration, MappedStatement, Object... params); 实际上执行JDBC代码
涉及到的设计模式:
Builder构建者设计模式、工厂模式、代理模式
# 自定义框架实现
# 客户端/使用端
在使用端项目中创建并配置以下文件:
sqlMapConfig.xml
:
<configuration>
<!--数据库连接信息-->
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8"></property>
<property name="username" value="root"></property>
<property name="password" value="123456"></property>
<!--引入SQL配置信息-->
<mapper resource="UserMapper.xml"></mapper>
</configuration>
UserMapper.xml
:
<mapper namespace="user">
<select id="selectOne" parameterType="com.example.hello.ipersistence.entity.User"
resultType="com.example.hello.ipersistence.entity.User">
select * from user where id = #{id} and username = #{username}
</select>
<select id="selectList" resultType="com.example.hello.ipersistence.entity.User">
select * from user
</select>
</mapper>
User
实体(省略setter、getter、toString):
public class User {
private String id;
private String username;
...
}
# 框架端
# 引入依赖
<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>
# 加载配置文件
编写Resources负责加载配置文件流:
public class Resources {
// 根据配置文件路径,将配置文件加载成字节流,存储在内存中
public static InputStream getResourceAsSteam(String path){
return Resources.class.getClassLoader().getResourceAsStream(path);
}
}
编写Configuration
负责存储配置文件中的配置信息:
public class Configuration {
// 数据源
private DataSource dataSource;
// map集合: key: statementId value: MappedStatement
private Map<String, MappedStatement> mappedStatementMap = new HashMap<>();
// 省略setter and getter
......
}
编写MappedStatement
负责保存每个Mapper中编写的sql片段信息:
public class MappedStatement {
// mapper sql id
private Integer id;
// sql语句
private String sql;
// 输入参数
private Class<?> parameterType;
// 输出参数
private Class<?> resultType;
// 省略setter and getter
......
}
# 解析配置文件
编写SqlSessionFactoryBuilder
负责(使用XMLConfigBuilder
)解析配置文件以及创建sqlSessionFactory
:
public class SqlSessionFactoryBuilder {
public SqlSessionFactory build(InputStream inputStream) throws DocumentException, PropertyVetoException, ClassNotFoundException {
// 1. 解析配置文件,封装Configuration
XMLConfigBuilder xmlConfigBuilder = new XMLConfigBuilder();
Configuration configuration = xmlConfigBuilder.parseConfiguration(inputStream);
// 2. 创建sqlSessionFactory
SqlSessionFactory sqlSessionFactory = new DefaultSqlSessionFactory(configuration);
return sqlSessionFactory;
}
}
编写XMLConfigBuilder
解析sqlMapConfig.xml
文件的具体逻辑:
public class XMLConfigBuilder {
private Configuration configuration;
public XMLConfigBuilder() {
this.configuration = new Configuration();
}
/**
* 解析配置文件
*/
public Configuration parseConfiguration(InputStream inputStream) throws DocumentException, PropertyVetoException, ClassNotFoundException {
Document document = new SAXReader().read(inputStream);
// <configuration> root
Element rootElement = document.getRootElement();
List<Element> propertyElements = rootElement.selectNodes("//property");
// <property>
Properties properties = new Properties();
for (Element propertyElement : propertyElements) {
String name = propertyElement.attributeValue("name");
String value = propertyElement.attributeValue("value");
properties.setProperty(name,value);
}
// 连接池
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> 拿到字节输入流,进一步解析
List<Element> mapperElements = rootElement.selectNodes("//mapper");
for (Element mapperElement : mapperElements) {
String mapperPath = mapperElement.attributeValue("resource");
InputStream resourceAsSteam = Resources.getResourceAsSteam(mapperPath);
XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
xmlMapperBuilder.parse(resourceAsSteam);
}
return configuration;
}
}
编写XMLMapperBuilder
解析相关Mapper.xml
文件:
public class XMLMapperBuilder {
private Configuration configuration;
public XMLMapperBuilder(Configuration configuration) {
this.configuration = configuration;
}
/**
* 解析SQL Mapper文件封装到mappedStatementMap
*/
public void parse(InputStream inputStream) throws DocumentException, ClassNotFoundException {
Document document = new SAXReader().read(inputStream);
Element rootElement = document.getRootElement();
String namespace = rootElement.attributeValue("namespace");
List<Element> select = rootElement.selectNodes("select");
// mappedStatement handle
for (Element element : select) {
String id = element.attributeValue("id");
String parameterType = element.attributeValue("parameterType");
String resultType = element.attributeValue("resultType");
Class<?> parameterTypeClass = getClassType(parameterType);
Class<?> resultTypeClass = getClassType(resultType);
String key = namespace + "." + id;
String textTrim = element.getTextTrim();
MappedStatement mappedStatement = new MappedStatement();
mappedStatement.setId(id);
mappedStatement.setParameterType(parameterTypeClass);
mappedStatement.setResultType(resultTypeClass);
mappedStatement.setSql(textTrim);
configuration.getMappedStatementMap().put(key , mappedStatement);
}
}
private Class<?> getClassType(String parameterTypeType) throws ClassNotFoundException {
return parameterType != null ? Class.forName(parameterType) : null;
}
}
# SqlSessionFactory接口以及实现
编写sqlSessionFactory
接⼝及DefaultSqlSessionFactory
实现类:
public interface SqlSessionFactory {
public SqlSession openSession();
}
public class DefaultSqlSessionFactory implements SqlSessionFactory{
private Configuration configuration;
public DefaultSqlSessionFactory(Configuration configuration) {
this.configuration = configuration;
}
@Override
public SqlSession openSession() {
return new DefaultSqlSession(configuration);
}
}
# SqlSession接口及实现
编写SqlSession
接⼝及DefaultSqlSession
实现类:
public interface SqlSession {
<E> List<E> selectList(String statementId, Object... param) throws Exception;
<T> T selectOne(String statementId,Object... params) throws Exception;
void close() throws SQLException;
}
public class DefaultSqlSession implements SqlSession {
private Configuration configuration;
private Executor simpleExecutor = new SimpleExecutor();
public DefaultSqlSession(Configuration configuration) {
this.configuration = configuration;
}
@Override
public <E> List<E> selectList(String statementId, Object... param) throws Exception {
MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
List<E> query = simpleExecutor.query(configuration, mappedStatement, param);
return query;
}
@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("select one, but find more");
}
}
@Override
public void close() throws SQLException {
simpleExecutor.close();
}
}
# Executor接口以及实现
public interface Executor {
<E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object[] param) throws Exception;
void close() throws SQLException;
}
public class SimpleExecutor implements Executor{
private Connection connection = null;
@Override
public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object[] param) throws Exception {
// 获取连接
connection = configuration.getDataSource().getConnection();
// select * from user where id = #{id} and username = #{username}
String sql = mappedStatement.getSql();
// 对sql进⾏处理, 转换为JDBC能处理的一些信息
BoundSql boundsql = getBoundSql(sql);
// select * from where id = ? and username = ?
String finalSql = boundsql.getSqlText();
// 获取传⼊参数类型
Class<?> parameterType = mappedStatement.getparameterType();
// 获取预编译preparedStatement对象
PreparedStatement preparedStatement = connection.prepareStatement(finalSql);
List<ParameterMapping> parameterMappingList = boundsql.getParameterMappingList();
for (int i = 0; i < parameterMappingList.size(); i++) {
ParameterMapping parameterMapping = parameterMappingList.get(i);
String name = parameterMapping.getContent();
// 反射
Field declaredField = parameterType.getDeclaredField(name);
declaredField.setAccessible(true);
// 参数的值
Object o = declaredField.get(param[0]);
// 给占位符赋值
preparedStatement.setObject(i + 1, o);
}
// 执行sql
ResultSet resultSet = preparedStatement.executeQuery();
// 封装返回结果集
Class<?> resultType = mappedStatement.getResultType();
List<E> results = new ArrayList<>();
while (resultSet.next()) {
Object o = resultType.newInstance();
// 元数据
ResultSetMetaData metaData = resultSet.getMetaData();
for (int i = 1; i <= metaData.getColumnCount(); i++) {
// 属性名
String columnName = metaData.getColumnName(i);
// 属性值
Object value = resultSet.getObject(columnName);
// 创建属性描述器,为属性⽣成读写⽅法,即使用反射或者内省,根据数据库表和实体的对应关系,完成封装
PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultType);
//获取写⽅法
Method writeMethod = propertyDescriptor.getWriteMethod();
//向类中写⼊值
writeMethod.invoke(o, value);
}
results.add((E)o);
}
return results;
}
/**
* 完成对#{}的解析工作:1.将#{}使用?代替 ,2.解析出#{}里面的值进行存储
*/
private BoundSql getBoundSql(String sql) {
// 标记处理类:主要是配合通⽤标记解析器GenericTokenParser类完成对配置⽂件等的解析⼯作,其中TokenHandler主要完成处理
ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
// GenericTokenParser :通⽤的标记解析器,完成了代码⽚段中的占位符的解析,然后再根据给定的标记处理器(TokenHandler)来进⾏表达式的处理
// 三个参数:分别为openToken (开始标记)、closeToken (结束标记)、handler (标记处理器)
GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
String parse = genericTokenParser.parse(sql);
List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();
return new BoundSql(parse, parameterMappings);
}
@Override
public void close() throws SQLException {
connection.close();
}
}
BoundSql
主要负责存储解析后的sql语句以及参数信息:
public class BoundSql {
// 解析过后的sql语句
private String sqlText;
// 解析出来的参数
private List<ParameterMapping> parameterMappingList;
public BoundSql(String sqlText, List<ParameterMapping> parameterMappingList) {
this.sqlText = sqlText;
this.parameterMappingList = parameterMappingList;
}
public String getSqlText() {
return sqlText;
}
public void setSqlText(String sqlText) {
this.sqlText = sqlText;
}
public List<ParameterMapping> getParameterMappingList() {
return parameterMappingList;
}
public void setParameterMappingList(List<ParameterMapping> parameterMappingList) {
this.parameterMappingList = parameterMappingList;
}
}
# 引入工具类
上述GenericTokenParser
、ParameterMapping
、ParameterMappingTokenHandler
、TokenHandler
均为MyBaits的源码之一,这里我们直接拷贝,作为utils
引入:
/**
* @author Clinton Begin
*/
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 "";
}
// search open token
// 下面继续验证是否包含开始标签,如果不包含,默认不是占位符,直接原样返回即可,否则继续执行。
int start = text.indexOf(openToken);
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;
do {
// 判断如果开始标记前如果有转义字符,就不作为openToken进行处理,否则继续处理
if (start > 0 && src[start - 1] == '\\') {
// this open token is escaped. remove the backslash and continue.
builder.append(src, offset, start - offset - 1).append(openToken);
offset = start + openToken.length();
} else {
// found open token. let's search close token. 重置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);
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);
} while (start > -1);
if (offset < src.length) {
builder.append(src, offset, src.length - offset);
}
return builder.toString();
}
}
public class ParameterMapping {
private String content;
public ParameterMapping(String content) {
this.content = content;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
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;
}
public List<ParameterMapping> getParameterMappings() {
return parameterMappings;
}
public void setParameterMappings(List<ParameterMapping> parameterMappings) {
this.parameterMappings = parameterMappings;
}
}
/**
* @author Clinton Begin
*/
public interface TokenHandler {
String handleToken(String content);
}
# 客户端测试用例
public class IPersistenceTest {
private SqlSession sqlSession;
@Before
public void before() throws Exception {
InputStream resourceAsSteam = Resources.getResourceAsSteam("sqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsSteam);
sqlSession = sqlSessionFactory.openSession();
}
@Test
public void testSelectList() throws Exception {
User user = new User();
user.setId(1);
user.setUsername("jack");
List<User> userList = sqlSession.selectList("user.selectList");
for (User user1 : userList) {
System.out.println(user1);
}
sqlSession.close();
}
@Test
public void testSelectOne() throws Exception {
User user = new User();
user.setId(1);
user.setUsername("jack");
User user2 = sqlSession.selectOne("user.selectOne", user);
System.out.println(user2);
sqlSession.close();
}
}
# ⾃定义框架优化
上述的⾃定义框架,我们解决了JDBC操作数据库带来的⼀些问题:例如频繁创建释放数据库连接,硬编码,⼿动封装返回结果集等问题,但是现在我们继续来分析刚刚完成的⾃定义框架代码(Test中的方法通常在DAO实现类中编写),会发现以下问题:
DAO的实现类中存在重复的代码,整个操作的过程模板重复(创建sqlSession,调⽤sqlSession⽅法,关闭 sqlSession)
DAO的实现类中存在硬编码,调⽤sqlSession的⽅法时,参数statementId硬编码
解决思路:使⽤代理模式来创建接⼝的代理对象
在SqlSession
接口中添加getMapper
:
public interface SqlSession {
// ......
<T> T getMapper(Class<?> mapperClass);
}
DefaultSqlSession
实现类:
@Override
public <T> T getMapper(Class<?> mapperClass) throws SQLException {
Object proxyInstance = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// selectOne / selectList
String methodName = method.getName();
// className : namespace
String className = method.getDeclaringClass().getName();
// statementId: namespace.id = 接口全限名.方法名 (修改对应的Mapper文件)
String key = className+"."+methodName;
// parameter & returnType
Type genericReturnType = method.getGenericReturnType();
//判断是否实现泛型类型参数化
if(genericReturnType instanceof ParameterizedType){
return selectList(key, args);
}
return selectOne(key, args);
}});
return (T)proxyInstance;
}
测试类:
public class IPersistenceTest {
// ......
@Test
public void testSelectListByProxy() throws Exception {
IUserDao userDao = sqlSession.getMapper(IUserDao.class);
List<User> userList = userDao.selectList();
for (User user1 : userList) {
System.out.println(user1);
}
}
@Test
public void testSelectOneByProxy() throws Exception {
User user = new User();
user.setId(1);
user.setUsername("jack");
IUserDao userDao = sqlSession.getMapper(IUserDao.class);
User user2 = userDao.selectOne(user);
System.out.println(user2);
}
}