自定义持久层框架
1、JDBC 的不足
2、自定义持久层框架设计思路及实现
使用端:(项目):引入自定义持久层框架的jar包
提供两部分配置信息:数据库配置信息,sql配置信息:sql语句、参数类型、返回值类型。
使用配置文件来提供这两部分配置信息:
- sqlMapConfig.xml:存放数据库配置信息,存放 mapper.xml 的全路径
- mapper.xml:存放 sql 配置信息
sqlMapConfig.xml(数据库配置文件)
<configuration>
<!--数据库配置信息-->
<datasource>
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql:///zdy_mybatis"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</datasource>
<!--存放 mapper.xml 的全路径-->
<mapper resource="UserMapper.xml"></mapper>
</configuration>
mapper.xml(sql配置信息)——商品模块
<mapper namespace="product">
</mapper>
mapper.xml——用户模块
<mapper namespace="user">
<!--sql的唯一标识:namespace.id来共同组成:statementId-->
<select id="findAll" resultType="com.lagou.pojo.User">
select * from user
</select>
<!--
User user = new User();
user.setId(1);
user.setUserName("张三");
-->
<select id="findByCondition" resultType="com.lagou.pojo.User" parameterType="com.lagou.pojo.User">
select * from user where id = #{id} and username = #{username}
</select>
</mapper>
User(pojo 实体类)
@Data
@AllArgumentsConstruct
@NoArgumentsConstruct
public class User implements Serializable {
private Long id;
private String username;
}
测试类
package com.lagou.test;
import com.lagou.dao.IUserDao;
import com.lagou.io.Resources;
import com.lagou.pojo.User;
import com.lagou.sqlSession.SqlSession;
import com.lagou.sqlSession.SqlSessionFactory;
import com.lagou.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(1L);
user.setUsername("张三");
// User user2 = sqlSession.selectOne("user.selectOne", user);
// System.out.println("user2 = " + user2);
List<User> users = sqlSession.selectList("user.selectList");
users.forEach(System.out::println);
}
}
自定义持久层框架本身:(工程):本质就是对JDBC代码进行了封装
- 加载配置文件:根据配置文件的路径,加载配置文件成字节输入流,存储在内存中
创建Resources类 方法:InputStream getResourceAsStream(String path)
package com.lagou.io;
import java.io.InputStream;
public class Resources {
public static InputStream getResourceAsStream(String path) {
// 根据配置文件的路径将配置文件加载成字节输入流存储在内存中
InputStream resourceAsStream = Resources.class.getClassLoader().getResourceAsStream(path);
return resourceAsStream;
}
}
- 创建两个JavaBean:(容器对象):存放的就是对配置文件解析出来的内容
Configuration:核心配置类:存放sqlMapConfig.xml解析出来的内容
MappedStatement:映射配置类:存放在mapper.xml解析出来的内容
package com.lagou.pojo;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
public class Configuration {
private DataSource dataSource;
/**
* key:statementId:sql的唯一标识:namespace.id组成
* value:就是封装好的MappedStatement对象
*/
private Map<String, MappedStatement> mappedStatementMap = new HashMap<String, MappedStatement>();
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;
}
}
package com.lagou.pojo;
public class MappedStatement {
// id标识
private String id;
// 返回值类型
private String resultType;
// 参数类型
private String parameterType;
// sql语句
private String sql;
public MappedStatement() {
}
public MappedStatement(String id, String resultType, String parameterType, String sql) {
this.id = id;
this.resultType = resultType;
this.parameterType = parameterType;
this.sql = sql;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getResultType() {
return resultType;
}
public void setResultType(String resultType) {
this.resultType = resultType;
}
public String getParameterType() {
return parameterType;
}
public void setParameterType(String parameterType) {
this.parameterType = parameterType;
}
public String getSql() {
return sql;
}
public void setSql(String sql) {
this.sql = sql;
}
}
- 解析
创建类:SqlSessionFactoryBuilder 方法:build(InputStream in)
第一:使用dom4j解析配置文件,将解析出来的内容封装到容器对象中
第二:创建SqlSessionFactory对象;生产SqlSession:会话对象(工厂模式)
<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.lagou</groupId>
<artifactId>IPersistence</artifactId>
<version>1.0-SNAPSHOT</version>
<!--只有将IPersistence进行打包才能导入到IPersistence_test中:maven的install指令-->
<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>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.31</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>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>
package com.lagou.sqlSession;
import com.lagou.config.XmlConfigBuilder;
import com.lagou.pojo.Configuration;
import java.io.InputStream;
public class SqlSessionFactoryBuilder {
public SqlSessionFactory build(InputStream in) throws Exception {
// 1、使用dom4j解析配置文件,将解析出来的内容装到Configuration中
XmlConfigBuilder xmlConfigBuilder = new XmlConfigBuilder();
Configuration configuration = xmlConfigBuilder.parseConfig(in);
// 2、创建SqlSession对象:工厂类:生产sqlSession:会话对象
DefaultSqlSessionFactory defaultSqlSessionFactory = new DefaultSqlSessionFactory(configuration);
return defaultSqlSessionFactory;
}
}
package com.lagou.config;
import com.lagou.io.Resources;
import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import com.mchange.v2.c3p0.ComboPooledDataSource;
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;
import java.util.Properties;
/**
* @author hhc19
* @date 2023/6/28 21:40
* @description
*/
public class XmlConfigBuilder {
private Configuration configuration;
public XmlConfigBuilder() {
this.configuration = new Configuration();
}
/**
* 该方法就是使用dom4j将配置文件进行解析,封装Configuration
*/
public Configuration parseConfig(InputStream inputStream) throws Exception {
Document document = new SAXReader().read(inputStream);
// <configuration>
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);
}
// c3p0的数据库连接池
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(properties.getProperty("driverClass"));
dataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
dataSource.setUser(properties.getProperty("username"));
dataSource.setPassword(properties.getProperty("password"));
configuration.setDataSource(dataSource);
// mapper.xml 解析:拿到路径——字节输入流——dom4j进行解析
List<Element> mapperNodes = rootElement.selectNodes("//mapper");
for (Element mapperNode : mapperNodes) {
String mapperConfigPath = mapperNode.attributeValue("resource");
InputStream resourceAsStream = Resources.getResourceAsStream(mapperConfigPath);
XmlMapperBuilder xmlMapperBuilder = new XmlMapperBuilder(configuration);
xmlMapperBuilder.parse(resourceAsStream);
}
return configuration;
}
}
public class XmlMapperBuilder {
private Configuration configuration;
public XmlMapperBuilder(Configuration configuration) {
this.configuration = configuration;
}
public void parse(InputStream inputStream) throws Exception {
Document document = new SAXReader().read(inputStream);
// <mapper>
Element element = document.getRootElement();
String namespace = element.attributeValue("namespace");
List<Element> selectNodes = element.selectNodes("//select"); // xpath 表达式
for (Element selectNode : selectNodes) {
String id = selectNode.attributeValue("id");
String resultType = selectNode.attributeValue("resultType");
String parameterType = selectNode.attributeValue("parameterType");
String sqlText = selectNode.getTextTrim();
MappedStatement mappedStatement = new MappedStatement(id, resultType, parameterType, sqlText);
String key = namespace + "." + id;
configuration.getMappedStatementMap().put(key, mappedStatement);
}
}
}
package com.lagou.sqlSession;
/**
* 基于开闭原则,此处创建接口,然后创建实现类来进行扩展
*/
public interface SqlSessionFactory {
SqlSession openSession();
}
- 创建SqlSessionFactory接口及实现类DefaultSqlSessionFactory
第一: openSession(): 生产sqlSession
package com.lagou.sqlSession;
import com.lagou.pojo.Configuration;
public class DefaultSqlSessionFactory implements SqlSessionFactory {
private Configuration configuration;
public DefaultSqlSessionFactory(Configuration configuration) {
this.configuration = configuration;
}
@Override
public SqlSession openSession() {
// configuration 核心配置类对象要一层一层的往下传递,直到Executor使用它来调用真正执行JDBC方法
return new DefaultSqlSession(configuration);
}
}
- 创建SqlSession接口及实现类DefaultSqlSession
定义对数据库的 crud 操作:selectList()
selectOne()
update()
delete()
package com.lagou.sqlSession;
import java.util.List;
public interface SqlSession {
// 查询所有
<E> List<E> selectList(String statementId, Object... params) throws Exception;
// 根据条件查询单个
<E> E selectOne(String statementId, Object... params) throws Exception;
}
package com.lagou.sqlSession;
import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Proxy;
import java.lang.reflect.Type;
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方法的调用
Executor executor = new SimpleExecutor();
MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
return executor.query(configuration, mappedStatement, params);
}
@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);
throw new RuntimeException("查询结果为空或者返回结果过多");
}
}
- 创建Executor接口及实现类SimpleExecutor实现类
query(Configuration, MappedStatement, Object... params)
:执行的就是JDBC代码
package com.lagou.sqlSession;
import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import java.util.List;
public interface Executor {
<E> List<E> query(Configuration configuration,
MappedStatement mappedStatement,
Object... params) throws Exception;
}
package com.lagou.sqlSession;
import com.lagou.config.BoundSql;
import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import com.lagou.utils.GenericTokenParser;
import com.lagou.utils.ParameterMapping;
import com.lagou.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}
String sql = mappedStatement.getSql();
// 转换sql语句:select * from user where id = ? and username = ?,转换的过程中,还需要对#{}里面的值进行解析存储
/**
* 为什么编写sql的时候不直接写?而是使用 #{} 的形式?
* 因为如果传递参数的时候是实体类型时,我们需要根据#{}中的参数名称来找到实体参数中对应属性的值来完成对占位符的赋值
*
* #{} 中的值不能乱写,应该与实体参数属性名称保持一致,只有这样我们才能找到对应的属性
*/
BoundSql boundSql = getBoundSql(sql);
// 3、获取预处理对象 preparedStatement
PreparedStatement statement = connection.prepareStatement(boundSql.getSqlText());
// 4、设置参数
String parameterType = mappedStatement.getParameterType(); // 获取参数类型的全路径
Class<?> parameterTypeClass = 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 field = parameterTypeClass.getDeclaredField(content);
// 暴力访问
field.setAccessible(true);
// get 方法表示的是从哪个实例对象中获取该 field 所对应的值
Object o = field.get(params[0]);
// 设置参数时,下标要从 1 开始
statement.setObject(i + 1, o);
}
// 5、执行sql
ResultSet resultSet = statement.executeQuery();
// 6、封装返回结果集
Class<?> resultClass = getClassType(mappedStatement.getResultType());
ArrayList<Object> resultList = new ArrayList<>();
while (resultSet.next()) {
Object result = resultClass.newInstance();
// 元数据
ResultSetMetaData metaData = resultSet.getMetaData();
// metaData.getColumnCount() 查询结果的总列数
for (int i = 1; i <= metaData.getColumnCount(); i++) {
// 字段名 下表从 1 开始
String columnName = metaData.getColumnName(i);
// 字段的值
Object columnValue = resultSet.getObject(columnName); // 根据名称获取对应的字段值
// 使用反射根据数据库表和实体的对应关系完成封装
// PropertyDescriptor 是类型库中的一个类,根据 columnName 在 resultClass 中生成对应属性的读写方法
PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultClass);
Method writeMethod = propertyDescriptor.getWriteMethod();
writeMethod.invoke(result, columnValue);
}
resultList.add(result);
}
return (List<E>) resultList;
}
private Class<?> getClassType(String parameterType) {
if (parameterType == null || parameterType.isEmpty()) return null;
Class parameterTypeClass;
try {
parameterTypeClass = Class.forName(parameterType);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
return parameterTypeClass;
}
/**
* 完成对 #{} 的解析工作:1.将 #{} 使用 ? 进行代替;2.解析出 #{} 里面的值进行存储
* @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();
return new BoundSql(parseSql, parameterMappings);
}
}
package com.lagou.config;
import com.lagou.utils.ParameterMapping;
import java.util.ArrayList;
import java.util.List;
public class BoundSql {
private String sqlText; // 解析过后的 sql
private List<ParameterMapping> parameterMappingList = new ArrayList<>(); // 解析过后的参数名称
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;
}
}
package com.lagou.utils;
/**
* @author hhc19
* @date 2023/6/28 23:50
* @description
*/
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和handlerToken()方法来实现
*/
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();
}
}
package com.lagou.utils;
/**
* @author hhc19
* @date 2023/6/29 0:18
* @description
*/
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;
}
}
package com.lagou.utils;
import java.util.ArrayList;
import java.util.List;
public class ParameterMappingTokenHandler implements TokenHandler {
private List<ParameterMapping> parameterMappings = new ArrayList<ParameterMapping>();
// context 是参数名称 #{id} #{name} 中的 id 和 name
@Override
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;
}
}
package com.lagou.utils;
public interface TokenHandler {
String handleToken(String content);
}
3、自定义持久层的不足
问题分析:
- Dao层使用自定义持久层框架,存在代码重复,整个操作的过程模板重复(加载配置文件、创建salSessionFactory、生产sqlSession)
- statementld存在硬编码问题
解决方案:使用代理模式生成Dao层接口的代理实现类
<mapper namespace="com.lagou.dao.IUserDao">
<!--namespace 的值要和接口的全限定名保持一致-->
<!--sql的唯一标识:namespace.id来共同组成:statementId-->
<select id="findAll" resultType="com.lagou.pojo.User">
select * from user
</select>
<!--
User user = new User();
user.setId(1);
user.setUserName("张三");
id 的值要和接口中的方法名保持一致
原因:在 InvocationHandler 的 invoke 方法中是无法获取到映射配置文件中配置的 namespace 和 id 的值的
但是可以在 invoke 方法中借助 method 对象获取到当前执行的方法名以及当前方法所在类的全限定名
-->
<select id="findByCondition" resultType="com.lagou.pojo.User" parameterType="com.lagou.pojo.User">
select * from user where id = #{id} and username = #{username}
</select>
</mapper>
package com.lagou.dao;
import com.lagou.pojo.User;
import java.util.List;
public interface IUserDao {
// 查询所有用户
List<User> findAll() throws Exception;
// 根据条件进行用户查询
User findByCondition(User user) throws Exception;
}
package com.lagou.dao.impl;
import com.lagou.dao.IUserDao;
import com.lagou.io.Resources;
import com.lagou.pojo.User;
import com.lagou.sqlSession.SqlSession;
import com.lagou.sqlSession.SqlSessionFactory;
import com.lagou.sqlSession.SqlSessionFactoryBuilder;
import java.io.InputStream;
import java.util.List;
public class UserDaoImpl 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();
// 调用
// statementId 硬编码问题
return sqlSession.selectList("user.selectList");
}
@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);
}
}
此时我们希望不写Dao层的实现类只写Dao接口,通过反射生成代理对象来调用存储在SqlSession的真正业务方法。
package com.lagou.test;
import com.lagou.dao.IUserDao;
import com.lagou.io.Resources;
import com.lagou.pojo.User;
import com.lagou.sqlSession.SqlSession;
import com.lagou.sqlSession.SqlSessionFactory;
import com.lagou.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(1L);
user.setUsername("张三");
// User user2 = sqlSession.selectOne("user.selectOne", user);
// System.out.println("user2 = " + user2);
List<User> users = sqlSession.selectList("user.selectList");
users.forEach(System.out::println);
}
@Test
public void test2() throws Exception {
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
// 调用
// 返回的其实就是一个代理对象,此处的 userDao 的类型就是一个 Proxy
// 代理对象调用 IUserDao 中的任意方法都要去执行 InvocationHandler 中的 invoke 方法
IUserDao userDao = sqlSession.getMapper(IUserDao.class);
User user = new User();
user.setId(2L);
user.setUsername("zhangsan");
User user2 = userDao.findByCondition(user);
System.out.println("user2 = " + user2);
}
}
package com.lagou.sqlSession;
import java.util.List;
/**
* @author hhc19
* @date 2023/6/28 22:53
* @description
*/
public interface SqlSession {
// 查询所有
<E> List<E> selectList(String statementId, Object... params) throws Exception;
// 根据条件查询单个
<E> E selectOne(String statementId, Object... params) throws Exception;
// 为 Dao 接口生成代理实现类
<T> T getMapper(Class<?> mapperClass);
}
package com.lagou.sqlSession;
import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Proxy;
import java.lang.reflect.Type;
import java.util.List;
/**
* @author hhc19
* @date 2023/6/28 22:54
* @description
*/
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方法的调用
Executor executor = new SimpleExecutor();
MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
return executor.query(configuration, mappedStatement, params);
}
@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);
throw new RuntimeException("查询结果为空或者返回结果过多");
}
@Override
public <T> T getMapper(Class<?> mapperClass) {
// 使用 JDK 动态代理来为 Dao 接口生成代理对象并返回
/** InvocationHandler 中 invoke 方法中 3个参数的作用
* proxy:当前代理对象的应用
* method:当前被调用方法的引用
* args:传递的参数
*/
Object proxyInstance = Proxy.newProxyInstance(mapperClass.getClassLoader(),
new Class[]{mapperClass},
(proxy, method, args) -> {
// 不管如何封装,如何优化,底层执行的都是 JDBC 代码,都被封装到了 SimpleExecutor 中的 query 方法中
// 根据不同情况调用 selectList或者selectOne,而不是直接调用 query 方法,让它们去调用 query 方法
// 准备参数 1:statementId:sql语句的唯一标识:namespace.id = 接口全限定名.方法名
// 方法名
String methodName = method.getName();
// 获取方法所在类的字节码对象,然后通过 getName 来获取该类的全限定名
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;
}
}