文章目录
1. 分析 JDBC 操作问题
JDBC
查询代码
package com.study.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class MyJdbc {
public static void main(String[] args) throws Exception {
// 加载数据库驱动
Class.forName("com.mysql.cj.jdbc.Driver");
// 通过驱动管理类获取数据库连接
Connection connection = DriverManager.getConnection("jdbc:mysql:///mybatis","root","12345678");
// 定义sql 语句 ?表示占位符
String sql = "SELECT * FROM user where id = ?";
// 获取预处理statement
PreparedStatement preparedStatement = connection.prepareStatement(sql);
// 设置参数,第一个参数为sql语句中参数的id(从1开始)
preparedStatement.setObject(1,1);
// 向数据库发出sql执行查询,查询出结果集
ResultSet resultSet = preparedStatement.executeQuery();
// 遍历查询结果
while (resultSet.next()) {
int id = resultSet.getInt("id");
String username = resultSet.getString("username");
System.out.println("id:" + id + "\nusername:" + username);
}
// 释放资源
resultSet.close();
preparedStatement.close();
connection.close();
}
}
2. 自定义持久层框架的思路
2.1. 手写持久层框架
- 创建使用端
persistence-test
的maven
项目
- 在
persistence-test
项目中创建SqlMapConfig.xml
<configuration>
<!--配置数据源-->
<dataSource>
<property name="driver" value="com.mysql.driver"/>
<!--本地数据库可以通过 '/' 来 替代 ip 和 port -->
<property name="url" value="jdbc:mysql:///mybatis"/>
<property name="username" value="root"/>
<property name="password" value="12345678"/>
</dataSource>
<!--存放mapper.xml 的 全路径,方便在持久层框架中通过 SqlMapConfig.xml 获取到 UserMapper.xml 等路径-->
<mapper resource="UserMapper.xml"/>
</configuration>
- 在
persistence-test
项目中创建UserMapper.xml
<mapper namespace="user">
<!--
1. sql的唯一标识由 namespace.id 来组成,称之为 statementId
2. resultType : 为了后面解析 sql 时,通过反射和内省技术,用全类名为 对应的对象赋值
3. parameterType :通过反射,取到参数全路径里面的某个值,为了知道获取某个值,所以要使用#{},代替?
-->
<select id="selectList" resultType="com.study.pojo.User">
SELECT * FROM user
</select>
<select id="selectOne" parameterType="com.study.pojo.User" resultType="com.study.pojo.User">
SELECT * FROM user WHERE id = #{id} and username = #{username}
</select>
</mapper>
- 创建自定义持久层项目
persistence
- 在
persistence
项目中创建Resources.java
package com.study.io;
import java.io.InputStream;
public class Resources {
// 根据配置文件的路径,将配置文件加载成字节输入流,存储到内存中
public static InputStream getResourceAsStream(String path){
return Resources.class.getClassLoader().getResourceAsStream(path);
}
}
- 在
persistence-test
项目中添加对persistence
的依赖
<?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.study</groupId>
<artifactId>persistence-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.study</groupId>
<artifactId>persistence</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
</project>
- 在
persistence-test
项目中编写测试类PersistenceTest.java
package com.study.test;
import com.study.io.Resources;
import java.io.InputStream;
public class IPersistenceTest {
public void test(){
InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
}
}
- 在
persistence
项目中创建MappedStatement.java
package com.study.pojo;
public class MappedStatement {
/**
* id 标识
*/
private String id;
/**
* 参数值类型
*/
private String parameterType;
/**
* 返回值类型
*/
private String resultType;
/**
* sql 语句
*/
private String sql;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getParameterType() {
return parameterType;
}
public void setParameterType(String parameterType) {
this.parameterType = parameterType;
}
public String getResultType() {
return resultType;
}
public void setResultType(String resultType) {
this.resultType = resultType;
}
public String getSql() {
return sql;
}
public void setSql(String sql) {
this.sql = sql;
}
}
- 在
persistence
项目中创建Configuration.java
package com.study.pojo;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
public class Configuration {
private DataSource dataSource;
/**
* key:statementId value:封装好的 MappedStatement 对象
*/
Map<String,MappedStatement> mappedStatementMap = new HashMap<>();
public DataSource getDataSource() {
return dataSource;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public Map<String, MappedStatement> getMappedStatementMap() {
return mappedStatementMap;
}
public void setMappedStatementMap(Map<String, MappedStatement> mappedStatementMap) {
this.mappedStatementMap = mappedStatementMap;
}
}
- 在
persistence
项目中添加相关依赖
<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>
- 在
persistence
项目中创建SqlSessionFactoryBuilder.java
package com.study.sqlsession;
import com.study.config.XmlConfigBuilder;
import com.study.pojo.Configuration;
import org.dom4j.DocumentException;
import java.beans.PropertyVetoException;
import java.io.InputStream;
public class SqlSessionFactoryBuilder {
public SqlSessionFactory build(InputStream inputStream) throws PropertyVetoException, DocumentException {
//第一步:使用dom4j 解析配置文件,将解析出来的内容封装到Configuration中
XmlConfigBuilder configBuilder = new XmlConfigBuilder();
Configuration configuration = configBuilder.parseConfig(inputStream);
//第二步:创建 SqlSessionFactory 对象
return null;
}
}
- 在
persistence
项目中创建SqlSessionFactory.java
接口
package com.study.sqlsession;
public interface SqlSessionFactory {
}
- 在
persistence
项目中创建XmlConfigBuilder.java
package com.study.config;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.study.io.Resources;
import com.study.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
*/
public Configuration parseConfig(InputStream inputStream) throws DocumentException, PropertyVetoException {
Document document = new SAXReader().read(inputStream);
Element rootElement = document.getRootElement();
List<Element> list = rootElement.selectNodes("//property");
Properties properties = new Properties();
for (Element element : list) {
String name = element.attributeValue("name");
String value = element.attributeValue("value");
properties.setProperty(name,value);
}
ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
comboPooledDataSource.setDriverClass(properties.getProperty("driver"));
comboPooledDataSource.setJdbcUrl(properties.getProperty("url"));
comboPooledDataSource.setUser(properties.getProperty("username"));
comboPooledDataSource.setPassword(properties.getProperty("password"));
configuration.setDataSource(comboPooledDataSource);
XmlMapperBuilder xmlMapperBuilder = new XmlMapperBuilder(configuration);
//mapper.xml 解析,拿到路径 -》 字节输入流 -》 dom4j 进行解析
List<Element> mapperList = rootElement.selectNodes("//mapper");
for (Element element : mapperList) {
String mapperPath = element.attributeValue("resource");
InputStream resourceAsStream = Resources.getResourceAsStream(mapperPath);
xmlMapperBuilder.parse(resourceAsStream);
}
return configuration;
}
}
- 在
persistence
项目中创建XmlMapperBuilder.java
package com.study.config;
import com.study.pojo.Configuration;
import com.study.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 read = new SAXReader().read(inputStream);
Element rootElement = read.getRootElement();
List<Element> list = rootElement.selectNodes("//select");
String namespace = rootElement.attributeValue("namespace");
for (Element element : list) {
String id = element.attributeValue("id");
String parameterType = element.attributeValue("parameterType");
String resultType = element.attributeValue("resultType");
String sql = element.getTextTrim();
MappedStatement mappedStatement = new MappedStatement();
mappedStatement.setId(id);
mappedStatement.setParameterType(parameterType);
mappedStatement.setResultType(resultType);
mappedStatement.setSql(sql);
String statementId = namespace + "." + id;
configuration.getMappedStatementMap().put(statementId,mappedStatement);
}
}
}
- 修改
persistence-test
项目中的测试方法
- 修改
persistence
项目中的SqlSessionFactory.java
package com.study.sqlsession;
public interface SqlSessionFactory {
SqlSession openSession();
}
- 在
persistence
项目中创建DefaultSqlSessionFactory.java
package com.study.sqlsession;
import com.study.pojo.Configuration;
public class DefaultSqlSessionFactory implements SqlSessionFactory {
private Configuration configuration;
public DefaultSqlSessionFactory(Configuration configuration) {
this.configuration = configuration;
}
@Override
public SqlSession openSession() {
return new DefaultSqlSession(configuration);
}
}
- 在
persistence
项目中创建SqlSession.java
package com.study.sqlsession;
public interface SqlSession {
}
- 在
persistence
项目中创建DefaultSqlSession.java
package com.study.sqlsession;
import com.study.pojo.Configuration;
public class DefaultSqlSession implements SqlSession {
private Configuration configuration;
public DefaultSqlSession(Configuration configuration) {
this.configuration = configuration;
}
}
- 修改
persistence
项目中的SqlSessionFactoryBuilder.java
import com.study.config.XmlConfigBuilder;
import com.study.pojo.Configuration;
import org.dom4j.DocumentException;
import java.beans.PropertyVetoException;
import java.io.InputStream;
public class SqlSessionFactoryBuilder {
public SqlSessionFactory build(InputStream inputStream) throws PropertyVetoException, DocumentException {
//第一步:使用dom4j 解析配置文件,将解析出来的内容封装到Configuration中
XmlConfigBuilder configBuilder = new XmlConfigBuilder();
Configuration configuration = configBuilder.parseConfig(inputStream);
//第二步:创建 SqlSessionFactory 对象
SqlSessionFactory sqlSessionFactory = new DefaultSqlSessionFactory(configuration);
return sqlSessionFactory;
}
}
- 修改
persistence-test
项目中的测试方法内容
- 修改
persistence
项目中SqlSession.java
package com.study.sqlsession;
import java.util.List;
public interface SqlSession {
// 查询全部
<E> List<E> selectList(String statementId,Object... params) throws Exception;
// 查询一个
<T> T selectOne(String statementId,Object... params) throws Exception;
}
- 修改
persistence
项目中DefaultSqlSession.java
package com.study.sqlsession;
import com.study.pojo.Configuration;
import com.study.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<Object> list = simpleExecutor.query(configuration, mappedStatement, params);
return (List<E>) 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("查询结果过多");
}
}
}
- 在
persistence
项目中创建Executor.java
接口
package com.study.sqlsession;
import com.study.pojo.Configuration;
import com.study.pojo.MappedStatement;
import java.util.List;
public interface Executor {
<E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object... params);
}
- 在
persistence
项目中创建SimpleExecutor.java
package com.study.sqlsession;
import com.study.pojo.Configuration;
import com.study.pojo.MappedStatement;
import java.util.List;
public class SimpleExecutor implements Executor {
@Override
public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object... params) {
return null;
}
}
- 在
persistence-test
项目中创建User.java
package com.study.pojo;
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 + '\'' +
'}';
}
}
- 修改
persistence-test
项目中的测试类
- 在
persistence
项目中添加utils
包下的内容
GenericTokenParser.java
/**
* Copyright 2009-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.study.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 "";
}
// 下面继续验证是否包含开始标签,如果不包含,默认不是占位符,直接原样返回即可,否则继续执行。
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();
}
}
ParameterMappingTokenHandler.java
package com.study.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;
}
public List<ParameterMapping> getParameterMappings() {
return parameterMappings;
}
public void setParameterMappings(List<ParameterMapping> parameterMappings) {
this.parameterMappings = parameterMappings;
}
}
TokenHandler.java
/**
* Copyright 2009-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.study.utils;
/**
* @author Clinton Begin
*/
public interface TokenHandler {
String handleToken(String content);
}
- 在
persistence
项目中创建ParameterMapping.java
package com.study.utils;
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;
}
}
- 在
persistence
项目中创建BoundSql.java
package com.study.config;
import com.study.utils.ParameterMapping;
import java.util.ArrayList;
import java.util.List;
public class BoundSql {
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;
}
}
- 修改
SimpleExecutor.java
中的query
方法
package com.study.sqlsession;
import com.study.config.BoundSql;
import com.study.pojo.Configuration;
import com.study.pojo.MappedStatement;
import com.study.utils.GenericTokenParser;
import com.study.utils.ParameterMapping;
import com.study.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 {
/**
* query 方法中主要写一段 jdbc 来执行sql
*/
@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<?> classType = getClassType(parameterType);
List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
for (int i = 0; i < parameterMappingList.size(); i++) {
ParameterMapping parameterMapping = parameterMappingList.get(i);
String content = parameterMapping.getContent();
//反射
Field declaredField = classType.getDeclaredField(content);
//设置暴力访问
declaredField.setAccessible(true);
Object o = declaredField.get(params[0]);
preparedStatement.setObject(i+1,o);
}
// 5. 执行sql
ResultSet resultSet = preparedStatement.executeQuery();
String resultType = mappedStatement.getResultType();
Class<?> resultTypeClass = getClassType(resultType);
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;
}
private Class<?> getClassType(String parameterType) throws ClassNotFoundException {
if(parameterType != null){
Class<?> aClass = Class.forName(parameterType);
return aClass;
}
return null;
}
/**
* 完成对#{}的解析工作:1.将#{}使用?进行代替,2.解析出#{}里面的值进行存储
*/
private BoundSql getBoundSql(String sql) {
//标记处理类:配置标记解析器来完成对占位符的解析处理工作
ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
GenericTokenParser genericTokenParser = new GenericTokenParser("#{","}",parameterMappingTokenHandler);
//解析出来的sql
String parseSql = genericTokenParser.parse(sql);
//#{}里面解析出来的参数名称
List<ParameterMapping> parameterMappingList = parameterMappingTokenHandler.getParameterMappings();
BoundSql boundSql = new BoundSql(parseSql,parameterMappingList);
return boundSql;
}
}
- 在
persistence-test
项目中修改测试类进行测试
package com.study.test;
import com.study.io.Resources;
import com.study.pojo.User;
import com.study.sqlsession.SqlSession;
import com.study.sqlsession.SqlSessionFactory;
import com.study.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.openSession();
User user = new User();
user.setId(2);
user.setUsername("Tom");
/*User user1 = sqlSession.selectOne("user.selectOne", user);
System.out.println(user1);*/
List<User> userList = sqlSession.selectList("user.selectList");
System.out.println(userList);
}
}
2.2. 对手写的持久层框架进行优化
2.2.1. 将查询封装到持久层
- 在
persistence-test
项目中添加IUser.Dao
接口
package com.study.dao;
import com.study.pojo.User;
import java.util.List;
public interface IUserDao {
//查询所有用户
List<User> findAll() throws Exception;
//根据条件进行用户查询
User findByCondition(User user) throws Exception;
}
- 在
persistence-test
项目中添加IUser.Dao
接口的实现类IUserDaoImpl.java
package com.study.dao;
import com.study.io.Resources;
import com.study.pojo.User;
import com.study.sqlsession.SqlSession;
import com.study.sqlsession.SqlSessionFactory;
import com.study.sqlsession.SqlSessionFactoryBuilder;
import java.io.InputStream;
import java.util.List;
public class IUserDaoImpl implements IUserDao {
@Override
public List<User> findAll() throws Exception {
InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
List<User> userList = sqlSession.selectList("user.selectList");
return userList;
}
@Override
public User findByCondition(User user) throws Exception {
InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
return sqlSession.selectOne("user.selectOne",user);
}
}
- 上述优化存在的问题,及解决方案分析
2.2.2. 通过动态代理优化硬编码等问题
- 修改
persistence
项目中的SqlSession.java
package com.study.sqlsession;
import java.util.List;
public interface SqlSession {
// 查询全部
<E> List<E> selectList(String statementId,Object... params) throws Exception;
// 查询一个
<T> T selectOne(String statementId,Object... params) throws Exception;
//为Dao接口生成代理实现类
<T> T getMapper(Class<?> mapperClass);
}
- 修改
persistence
项目中的DefaultSqlSession.java
package com.study.sqlsession;
import com.study.pojo.Configuration;
import com.study.pojo.MappedStatement;
import java.lang.reflect.*;
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<Object> list = simpleExecutor.query(configuration, mappedStatement, params);
return (List<E>) 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("查询结果过多");
}
}
@Override
public <T> T getMapper(Class<?> mapperClass) {
// 使用JDK动态代理来为Dao接口生成代理对象,并返回
Object proxyInstance = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// 底层都还是去执行JDBC代码 //根据不同情况,来调用selctList或者selectOne
// 准备参数 1:statmentid :sql语句的唯一标识:namespace.id= 接口全限定名.方法名
// 方法名:findAll
String name = method.getName();
String className = method.getDeclaringClass().getTypeName();
String statementId = className + "." + name;
// 准备参数2:params:args
// 获取被调用方法的返回值类型
Type genericReturnType = method.getGenericReturnType();
// 判断是否进行了 泛型类型参数化
if(genericReturnType instanceof ParameterizedType){
List<Object> objects = selectList(statementId);
return objects;
}
return selectOne(statementId, args);
}
});
return (T) proxyInstance;
}
}
- 修改
persistence-test
项目中的UserMapper.xml
的命名空间和id,使之与接口中保持一致
<mapper namespace="com.study.dao.IUserDao">
<select id="findAll" resultType="com.study.pojo.User">
select * from user
</select>
<select id="findByCondition" parameterType="com.study.pojo.User" resultType="com.study.pojo.User">
select * from user where id = #{id} and username = #{username}
</select>
</mapper>
- 修改
persistence-test
项目中的测试方法
package com.study.test;
import com.study.dao.IUserDao;
import com.study.io.Resources;
import com.study.pojo.User;
import com.study.sqlsession.SqlSession;
import com.study.sqlsession.SqlSessionFactory;
import com.study.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.openSession();
IUserDao userDao = sqlSession.getMapper(IUserDao.class);
User user = new User();
user.setUsername("Tom");
user.setId(2);
User user1 = userDao.findByCondition(user);
System.out.println(user1);
List<User> all = userDao.findAll();
System.out.println(all);
}
}