一、自定义持久层MyBatis框架
1.1. 分析JDBC操作的问题
public class JDBCTest {
public static void main(String[] args) throws Exception {
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();
// 遍历查询结果集
User user = new User();
while (resultSet.next()) {
Long id = resultSet.getLong("id");
String username = resultSet.getString("username");
// 封装User
user.setId(id);
user.setName(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问题总结
原始JDBC存在的问题如下:
- 数据库连接创建、释放频繁造成系统资源浪费,从而影响系统性能。
- SQL语句在代码中硬编码,造成代码不易维护,实际应用中SQL变化的可能较大,SQL需要改变Java代码。
- 使用PreparedStatement向占有位符号传参数存在硬编码,因为SQL语句的where条件不一定,可能多也可能少,修改SQL还要修改代码,系统不易维护。
- 对结果集解析存在硬编码(查询列名),SQL变化导致解析代码变化,系统不易维护,如果能将数据库记录封装成POJO对象解析比较方便。
1.2. 问题解决思路
- 使用数据库连接池初始化连接资源。
- 将sql语句抽取到xml配置文件中。
- 使用反射、内省等底层技术,自动将实体与表进行属性与字段的自动映射。
1.3. 自定义框架设计
使用端:提供核心配置文件:
- sqlMapConfig.xml : 存放数据源信息,引入mapper.xml
- Mapper.xml : sql语句的配置文件信息
框架端:
- 读取配置文件
读取完成以后以流的形式存在,我们不能将读取到的配置信息以流的形式存放在内存中,不好操作,可以创建javaBean来存储
(1)Configuration
: 存放数据库基本信息、Map<唯一标识,Mapper> 唯一标识:namespace + “.” +id
(2)MappedStatement
:sql语句、statement类型、输入参数java类型、输出参数java类型 - 解析配置文件
创建SqlSessionFactoryBuilder
类:
方法:SqlSessionFactory build():
第一:使用dom4j解析配置文件,将解析出来的内容封装到Configuration
和MappedStatement
中
第二:创建SqlSessionFactory
的实现类DefaultSqlSession
- 创建
SqlSessionFactory
:
方法:openSession()
: 获取SqlSession接口的实现类实例对象 - 创建
SqlSession
接口及实现类:主要封装crud方法
方法:selectList(String statementId,Object param):查询所有
selectOne(String statementId,Object param):查询单个
具体实现:封装JDBC完成对数据库表的查询操作
涉及到的设计模式:Builder构建者设计模式、工厂模式、代理模式
1.4. 自定义框架实现
1.4.1. 在使用端项目中创建配置配置文件
创建 sqlMapConfig.xml
<configuration>
<!--数据库连接信息-->
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql:///zdy_mybatis"></property>
<property name="user" value="root"></property>
<property name="password" value="root"></property>
<!--引入sql映射配置信息-->
<mapper resource="UserMapper.xml"></mapper>
</configuration>
mapper.xml
<mapper namespace="User">
<select id="selectOne" paramterType="com.lagou.pojo.User"
resultType="com.lagou.pojo.User">
select * from user where id = #{id} and username =#{username}
</select>
<select id="selectList" resultType="com.lagou.pojo.User">
select * from user
</select>
</mapper>
User实体
public class User {
private Integer id;
private String username;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
'}';
}
}
1.4.2. 持久层框架代码
1、创建一个Maven子工程并且导入需要用到的依赖坐标
<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>
2、创建容器对象Configuration以及Mapper对象MapperStatement
Configuration
public class Configuration {
/**
* 数据源
*/
private DataSource dataSource;
/**
* key: statementId value:封装好的mappedStatement对象
* **Mapper.xml配置文件中,每一个<select><insert><update><delete>标签都对应一个MapperStatement
*/
private Map<String, MapperStatement> mapperStatementMap = new HashMap<>();
public DataSource getDataSource() {
return dataSource;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public Map<String, MapperStatement> getMapperStatementMap() {
return mapperStatementMap;
}
public void setMapperStatementMap(Map<String, MapperStatement> mapperStatementMap) {
this.mapperStatementMap = mapperStatementMap;
}
@Override
public String toString() {
return "Configuration{" +
"dataSource=" + dataSource +
", mapperStatementMap=" + mapperStatementMap +
'}';
}
}
MapperStatement
public class MapperStatement {
/**
* 标签id
*/
private String id;
/**
* 参数类型
*/
private Class<?> parameterType;
/**
* 返回值类型
*/
private Class<?> resultType;
/**
* sql语句(带有占位符的sql,后续需要对占位符进行解析,解析成 ?)
*/
private String sql;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Class<?> getParameterType() {
return parameterType;
}
public void setParameterType(Class<?> parameterType) {
this.parameterType = parameterType;
}
public Class<?> getResultType() {
return resultType;
}
public void setResultType(Class<?> resultType) {
this.resultType = resultType;
}
public String getSql() {
return sql;
}
public void setSql(String sql) {
this.sql = sql;
}
@Override
public String toString() {
return "MapperStatement{" +
"id='" + id + '\'' +
", parameterType='" + parameterType + '\'' +
", resultType='" + resultType + '\'' +
", sql='" + sql + '\'' +
'}';
}
}
3、为了方便对 xml 配置文件进行加载,需要编写资源加载类。
public class Resources {
/**
* 根据配置文件的路径,将配置文件加载成字节输入流,存储在内存中
*/
public static InputStream getResourceAsStream(String path) {
return Resources.class.getClassLoader().getResourceAsStream(path);
}
}
4、SqlSessionFactoryBuilder
public class SqlSessionFactoryBuilder {
public SqlSessionFactory build(InputStream inputStream) throws Exception {
// 第一:使用dom4j解析数据库配置文件,将解析出来的内容封装到Configuration中
XMLConfigBuilder xmlConfigBuilder = new XMLConfigBuilder();
Configuration configuration = xmlConfigBuilder.parse(inputStream);
// 第二:创建sqlSessionFactory对象:工厂类:生产sqlSession:会话对象
DefaultSqlSessionFactory defaultSqlSessionFactory = new DefaultSqlSessionFactory(configuration);
return defaultSqlSessionFactory;
}
}
5、XMLConfigBuilder,解析核心配置文件sqlMapConfig.xml,并存入Configuration容器对象中
public class XMLConfigBuilder {
private Configuration configuration;
/**
* 调用该构造方法的时候初始化Configuration对象
*/
public XMLConfigBuilder() {
configuration = new Configuration();
}
/**
* 解析数据库配置文件xml
*/
public Configuration parse(InputStream inputStream) throws Exception {
Document document = new SAXReader().read(inputStream);
// 获取根节点
Element rootElement = document.getRootElement();
// 获取根节点底下的所有property节点
List<Element> propertyList = rootElement.selectNodes("//property");
Properties properties = new Properties();
for (Element element : propertyList) {
String name = element.attributeValue("name");
String value = element.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.xml配置文件
List<Element> mapperList = rootElement.selectNodes("//mapper");
for (Element element : mapperList) {
String resource = element.attributeValue("resource");
InputStream resourceAsStream = Resources.getResourceAsStream(resource);
XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
xmlMapperBuilder.parse(resourceAsStream);
}
return configuration;
}
}
6、XMLMapperBuilder
public class XMLMapperBuilder {
private Configuration configuration;
public XMLMapperBuilder(Configuration configuration) {
this.configuration = configuration;
}
/**
* 解析mapper.xml配置文件,并设置到容器对象的mapperStatementMap中
*/
public Configuration parse(InputStream inputStream) throws Exception {
Document document = new SAXReader().read(inputStream);
Element rootElement = document.getRootElement();
String namespace = rootElement.attributeValue("namespace");
List<Element> selectList = rootElement.selectNodes("//select");
for (Element element : selectList) {
MapperStatement mapperStatement = new MapperStatement();
String id = element.attributeValue("id");
mapperStatement.setId(id);
// 输入参数class
String parameterType = element.attributeValue("parameterType");
Class<?> parameterTypeClass = getClassType(parameterType);
mapperStatement.setParameterType(parameterTypeClass);
//返回结果class
String resultType = element.attributeValue("resultType");
Class<?> resultTypeClass = getClassType(resultType);
mapperStatement.setResultType(resultTypeClass);
//sql语句
String sql = element.getTextTrim();
mapperStatement.setSql(sql);
//statementId
String statementId = namespace + "." + id;
//填充 configuration
configuration.getMapperStatementMap().put(statementId, mapperStatement);
}
return configuration;
}
private Class<?> getClassType(String classType) throws ClassNotFoundException {
Class<?> aClass = Class.forName(classType);
return aClass;
}
}
7、至此,核心配置文件已经解析完成并存放入Configuration对象中。 接下来创建sqlSessionFactory对象:工厂类:生产sqlSession:会话对象。
SqlSessionFactory
public interface SqlSessionFactory {
SqlSession openSession();
}
DefaultSqlSessionFactory
public class DefaultSqlSessionFactory implements SqlSessionFactory {
private Configuration configuration;
public DefaultSqlSessionFactory(Configuration configuration) {
this.configuration = configuration;
}
@Override
public SqlSession openSession() {
return new DefaultSqlSqlSession(configuration);
}
}
8、调用SqlSessionFactory的openSession()方法生产SqlSession
SqlSession
public interface SqlSession {
<E> List<E> selectList(String statementId, Object... params) throws Exception;
<E> E selectOne(String statementId, Object... params) throws Exception;
}
DefaultSqlSession
public class DefaultSqlSqlSession implements SqlSession {
private Configuration configuration;
public DefaultSqlSqlSession(Configuration configuration) {
this.configuration = configuration;
}
@Override
public <E> List<E> selectList(String statementId, Object... params) throws Exception {
MapperStatement mapperStatement = configuration.getMapperStatementMap().get(statementId);
if (mapperStatement != null) {
// 调用处理器对象Executor的query()方法
return new SimpleExecutor().query(configuration, mapperStatement, params);
} else {
return null;
}
}
@Override
public <E> E selectOne(String statementId, Object... params) throws Exception {
List<Object> objects = selectList(statementId, params);
if (objects.size() == 1) {
return (E) objects.get(0);
} else {
throw new RuntimeException("查询结果个数为0或者大于1");
}
}
}
9、Executor处理器,用来执行SQL语句
Executor
public interface Executor {
<E> List<E> query(Configuration configuration, MapperStatement mapperStatement, Object... params) throws Exception;
}
SimpleExecutor
public class SimpleExecutor implements Executor {
@Override
public <E> List<E> query(Configuration configuration, MapperStatement mapperStatement, Object... params) throws Exception {
// 获取数据源
DataSource dataSource = configuration.getDataSource();
// 建立连接
Connection connection = dataSource.getConnection();
// 此时的sql语句:select * from user where id = #{id} and username = #{username}
String sql = mapperStatement.getSql();
// 对sql进行处理
BoundSql boundSql = getBoundSql(sql);
// select * from where id = ? and username = ?
String finalSql = boundSql.getSql();
// 获取预编译preparedStatement对象
PreparedStatement preparedStatement = connection.prepareStatement(finalSql);
// 4. 设置参数
// 获取到了参数的全路径
Class<?> parameterTypeClass = mapperStatement.getParameterType();
// 占位符里面的信息
List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
for (int i = 0; i < parameterMappings.size(); i++) {
ParameterMapping parameterMapping = parameterMappings.get(i);
// 占位符字段名称
String content = parameterMapping.getContent();
//反射
Field declaredField = parameterTypeClass.getDeclaredField(content);
//暴力访问
declaredField.setAccessible(true);
//参数的值
Object o = declaredField.get(params[0]);
// 给占位符赋值
preparedStatement.setObject(i + 1, o);
}
// 5. 执行sql
ResultSet resultSet = preparedStatement.executeQuery();
// 返回结果类型
Class<?> resultTypeClass = mapperStatement.getResultType();
List<Object> objects = new ArrayList<>();
// 6. 封装返回结果集
while (resultSet.next()) {
Object o = resultTypeClass.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, resultTypeClass);
//获取写方法
Method writeMethod = propertyDescriptor.getWriteMethod();
//向类中写入值
writeMethod.invoke(o, value);
}
objects.add(o);
}
return (List<E>) objects;
}
/**
* 完成对#{}的解析工作:1.将#{}使用?进行代替,2.解析出#{}里面的值进行存储
*
* <p>
* 1、ParameterMappingTokenHandler:标记处理类,主要是配合通用标记解析器GenericTokenParser类完成对配置文件等的解析工作,
* 其中TokenHandler主要完成处理
* 2、GenericTokenParser :通用的标记解析器,完成了代码片段中的占位符的解析,然后再根据给定的标记处理器(TokenHandler)来进行表达式的处理
* 三个参数:分别为openToken (开始标记)、closeToken (结束标记)、handler (标记处理器)
*
* @param sql
* @return
*/
private BoundSql getBoundSql(String sql) {
// 标记处理类:配置标记解析器来完成对占位符的解析处理工作
ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
// 解析出来的sql
String parseSql = genericTokenParser.parse(sql);
// #{}里面解析出来的参数名称
List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();
BoundSql boundSql = new BoundSql(parseSql, parameterMappings);
return boundSql;
}
}
BoundSql
public class BoundSql {
private String sql;
private List<ParameterMapping> parameterMappings;
public BoundSql(String sql, List<ParameterMapping> parameterMappings) {
this.sql = sql;
this.parameterMappings = parameterMappings;
}
public String getSql() {
return sql;
}
public void setSql(String sql) {
this.sql = sql;
}
public List<ParameterMapping> getParameterMappings() {
return parameterMappings;
}
public void setParameterMappings(List<ParameterMapping> parameterMappings) {
this.parameterMappings = parameterMappings;
}
}
1.4.3. 使用端使用自定义持久层框架
1.4.3.1. 第一种方式:测试类
public class Test {
public static void main(String[] args) {
InputStream inputStream = Resources.getResourceAsStream("sqlMapperConfig.xml");
try {
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
User user = new User();
user.setId(1L);
user.setName("zhangsan");
User user1 = sqlSession.selectOne("user.selectOne", user);
System.out.println(user1);
List<User> users = sqlSession.selectList("user.selectList", null);
for (User user2 : users) {
System.out.println(user2);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
1.4.3.2. 第二种方式:使用接口+实现类
IUserDao
public interface IUserDao {
List<User> findAll();
User findOne(User user);
}
UserDaoImpl
public class UserDaoImpl implements IUserDao {
public List<User> findAll() {
InputStream inputStream = Resources.getResourceAsStream("sqlMapperConfig.xml");
try {
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
List<User> users = sqlSession.selectList("user.selectList", null);
for (User user2 : users) {
System.out.println(user2);
}
return users;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public User findOne(User user) {
InputStream inputStream = Resources.getResourceAsStream("sqlMapperConfig.xml");
try {
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
User resultUser = sqlSession.selectOne("user.selectOne", user);
System.out.println(resultUser);
return resultUser;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
通过上述我们的自定义框架,我们解决了JDBC操作数据库带来的一些问题:例如频繁创建释放数据库连接,硬编码,手动封装返回结果集等问题,但是现在我们继续来分析刚刚完成的自定义框架代码,有没有什么问题?
问题如下:
1. dao的实现类中存在重复的代码,整个操作的过程模板重复(创建sqlsession,调用sqlsession方 法,关闭 sqlsession)
2. dao的实现类中存在硬编码,调用sqlsession的方法时,参数statement的id硬编码
解决:使用代理模式来创建接口的代理对象
1.4.4. 使用动态代理模式创建接口的代理对象
(1)SqlSession接口增加getMapper(Class<?> mapperClass)方法
public interface SqlSession {
<E> List<E> selectList(String statementId, Object... params) throws Exception;
<E> E selectOne(String statementId, Object... params) throws Exception;
/**
* 为Dao接口生成代理实现类
*
* @param mapperClass 接口类信息
* @param <E>
* @return
*/
<E> E getMapper(Class<?> mapperClass);
}
(2)DefaultSqlSession实现getMapper(Class<?> mapperClass)方法
public class DefaultSqlSqlSession implements SqlSession {
private Configuration configuration;
public DefaultSqlSqlSession(Configuration configuration) {
this.configuration = configuration;
}
@Override
public <E> List<E> selectList(String statementId, Object... params) throws Exception {
MapperStatement mapperStatement = configuration.getMapperStatementMap().get(statementId);
if (mapperStatement != null) {
return new SimpleExecutor().query(configuration, mapperStatement, params);
} else {
return null;
}
}
@Override
public <E> E selectOne(String statementId, Object... params) throws Exception {
List<Object> objects = selectList(statementId, params);
if (objects.size() == 1) {
return (E) objects.get(0);
} else {
throw new RuntimeException("查询结果个数为0或者大于1");
}
}
@Override
public <E> E getMapper(Class<?> mapperClass) {
// 使用JDK动态代理生成dao接口的实现类
Object proxyInstance = Proxy.newProxyInstance(DefaultSqlSqlSession.class.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
/**
* 代理对象调用接口中的任意方法,都会调用invoke()方法
* @param proxy 当前代理对象的引用
* @param method 当前被调用方法的引用
* @param args 传递的参数
* @return
* @throws Throwable
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
String methodName = method.getName();
String className = method.getDeclaringClass().getName();
String statementId = className + "." + methodName;
// 准备参数2:params:args
// 获取被调用方法的返回值类型
Type returnType = method.getGenericReturnType();
// 判断是否进行了 泛型类型参数化
if (returnType instanceof ParameterizedType) {
List<Object> objects = selectList(statementId, args);
return objects;
}
return selectOne(statementId, args);
}
});
return (E) proxyInstance;
}
}