在自定义持久层框架之前,我们先了解下持久层这个概念。持久层是 JavaEE 三层体系结构中与数据库交互的一层,通常也会被我们称之为 Dao 层。持久层的技术选型有很多(比如:JDBC、Hibernate、MyBatis、QueryDSL等)。
这里有个问题:既然 JDBC 可以完成数据库的交互,为什么还会出现各种持久层框架呢,比如 MyBatis?
猜想:使用原生的 JDBC 进行数据库交互,本身是不是会存在一些问题,所以持久层框架就是这些问题的解决方案。
我们接下来会做什么呢?
- 对 JDBC 的代码进行回顾
- 分析 JDBC 在与数据库交互时,存在哪些问题
- 针对问题,提供解决方案
- 在上面的基础上,完成自定义持久层框架
JDBC
对 JDBC 内容的回顾,以及问题分析。
下面是 jdbc 操作数据库的代码:
package com.orm;
import entity.User;
import java.sql.*;
public class JdbcDemo {
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()) {
int id = resultSet.getInt("id");
String username = resultSet.getString("username");
// 封装User
user.setId(id);
user.setUsername(username);
}
System.out.println(user);
} catch (Exception e) {
e.printStackTrace();
} finally {
// 释放资源
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
代码分析
在上面的代码中我们可以看到原生 JDBC 存在的一些问题:
- 数据库连接创建、释放频繁会造成系统资源的浪费,从而影响系统性能。
- SQL 语句在代码中硬编码,造成的代码不易维护,在实际的应用中 SQL 变化的可能较大, SQL 变动需要改变 java 代码。
- 使用 prepareStatement 向占位符传入参数存在硬编码,系统不易维护,如果能将数据库记录封装成 pojo 对象解析会比较方便。
- 需要手动封装结果集,比较繁琐。
sql 语句、设置参数、获取结果集均存在硬编码问题,硬编码问题我们第一反应就能想到使用配置文件。在这里停顿下,数据库的配置信息需要抽到配置文件中,而我们的 SQL 语句、设置参数等信息也需要抽到配置文件中,这两部分内容需要不需要抽取到同一个配置文件中呢?
虽然可以但是不建议这么做,我们知道数据库的配置信息肯定是不经常发生变更的,而 SQL 语句是经常会发生改变的。这两种配置通常不会放在同一个配置文件中。
手动封装结果集:我们可以使用反射、内省等技术。
解决思路
- 使用配置文件,处理数据库配置信息问题
- 采用数据库连接池管理数据库连接(c3p0、druid等)
- 使用配置文件解决 SQL 语句的硬编码问题,
手写持久层框架设计思路
上面我们对 JDBC 进行了回顾以及代码分析,现在我们开始设计一个简易的持久层框架。我们要明确一点的就是,持久层框架的本质是对 JDBC 的封装。只不过在封装的过程中,我们需要把 JDBC 存在的这些问题进行处理和规避。
我们可以将它分为两个部分,一个部分是框架的使用端,一个是持久层框架本身。把使用端看成是一个项目,在项目开发中会使用我们自己实现的持久层框架( jar 包)完成与数据库的交互。持久层框架本身也是一个过程,其本质是对 JDBC 代码进行封装。
持久层框架的使用端
我们思考一个问题,一段 JDBC 代码正常执行需要哪些条件?
其实有两部分信息是必须的:
- 数据库的配置信息(包含了:数据库的驱动类、具体哪个库、用户名和密码等)
- SQL 的配置信息(包含了:SQL 语句、参数、参数类型、返回值、返回值类型等)
这些信息应该由谁提供呢?
我们知道持久层框架是专门与数据库打交道的,只对外提供操作数据库的 API,那么在实现时不会将某个环境和数据库硬编码,这样会不灵活,所以把这些信息交给使用端,使用端要什么数据,自己去提供,框架拿到信息再去做相应的数据库操作。
可以使用配置文件提供数据库的配置信息和 SQL 相关的信息并且提供配置文件的地址信息:
- sqlMapConfig.xml 存放数据库的配置信息和 存放 mapper.xml 的全路径
- mapper.xml 存放 SQL 配置信息
持久层框架根据配置文件的地址,获取到配置文件,然后解析获取到数据库配置信息和 SQL 相关的信息。
持久层框架本身
-
加载配置文件---根据配置文件的路径,加载配置文件成字节输入流,存储在内存中
-
创建 Resource 类,提供 getResourceAsStream(String path)方法(path 就是上面配置文件的路径)
思考下:这里有两个配置文件,那么我需要执行两次解析配置文件的方法?
可以执行两次,有没有其它的方法呢,首先 sqlMapConfig.xml 是必须得解析的,那么我们是不是可以将 mapper.xml 的全路径信息配置在 sqlMapConfig.xml 中,这样的话使用端只需要提供 sqlMapConfig.xml 配置文件的全路径,在加载配置文件时就可以同时对 mapper.xml 文件进行加载。
在这一步我们仅仅是将配置文件加载成了流存储在内存中,但是数据在内存中不方便操作,我们可以结合面向对象的思想,将配置文件中的内容封装成两个 java bean。
-
创建两个 java bean,java bean 就是容器对象,存放配置文件解析出来的内容
- Configuration 核心配置类,主要存放 sqlMapConfig.xml 解析出来的内容
- MappedStatement 映射配置文件,主要存放 mapper.xml 解析出来的内容
-
解析配置文件
- dom4j 解析 xml 文件并将内容封装到容器对象中
- 创建 SqlSessionFacotryBuilder 类,提供 build(InputStream in) 方法。生产 SqlSession 会话对象(工厂模式)。
为什么不直接 new 获取 SqlSession,而是用 SqlSessionFacotryBuilder ?
使用工厂设计模式获取 SqlSession 会话对象,可以降低程序间的耦合还可以针对不同的需求生成不同状态的对象。
-
基于开闭原则,创建 SqlSessionFactory 接口及其实现类 DefaultSqlSessionFactory
-
创建 SqlSeesion 接口及其实现类 DefaultSqlSession
- 定义对数据库的 CRUD 操作:selectOne()、selectList()、update() 、delete()
- 创建 Executor 接口及其实现类 SimpleExecutor 实现类
- 将 JDBC 代码提取封装到 Executor 接口的实现类中()
- query(Configuration configuration,Object...params),执行 query 需要知道 SQL、参数、参数类型、返回的结果集类型等,而这些信息我们在上面已经封装在了 Configuration 中。
代码实现
1. 创建 maven 工程 simpormclient
- 创建 maven 工程 simpormclient
- 添加引入simporm 项目的 maven 依赖
<!--引入自定义持久层框架的依赖-->
<dependency>
<groupId>com.orm</groupId>
<artifactId>simporm</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
- 在 simpormclient 工程中,resources 目录添加 sqlMapConfig.xml 文件,并配置数据库的配置信息。
<configuration>
<datasource>
<properties name="driverClass" value="com.mysql.jdbc.Driver"></properties>
<properties name="jdbcUrl" value="jdbc:mysql://simporm"></properties>
<properties name="username" value="root"></properties>
<properties password="root" value="root"></properties>
</datasource>
<!-- 存放 mapper.xml 文件的全路径-->
<mapper resource="UserMapper.xml"></mapper>
</configuration>
- 添加 UserMapper.xml,配置 SQL 信息
<mapper namespace="user">
<!-- sql 的唯一标识:namespace.id 组成=statementId-->
<select id="selectUserList">
select * from user
</select>
<select id="selectOneUser" resultType="com.orm.User" paramterType="com.orm.User">
select * from user where id = #{id} and username =#{username}
</select>
</mapper>
2. 创建 maven 工程 simporm
在具体编写之前,先对自定义持久层框架做一个整体的回顾。持久层框架的本质是对 JDBC 的封装,所以底层执行的还是执行 JDBC 代码。那么正常执行 JDBC 代码需要满足哪些条件呢?有两部分信息必不可少,一个是数据库配置信息,另一个是 SQL 配置信息。这两个配置信息是由使用端提供的(sqlMapConfig.xml、mapper.xml)。我们需要使用 dom4j 对 xml 文件进行解析,并将解析出来的信息封装成 java bean 对象(Configuration、MappedStatement)。
3. 数据库脚本
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL,
`username` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL,
`sex` varchar(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
SET FOREIGN_KEY_CHECKS =
- 创建 maven 工程 simporm
- 定义 Resources 类
- pom 文件
<?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.orm</groupId>
<artifactId>simporm</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.encoding>UTF-8</maven.compiler.encoding>
<java.version>1.8</java.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.17</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
</dependency>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
<version>1.1.6</version>
</dependency>
</dependencies>
</project>
4. 定义 Resources 类
package com.orm.io;
import java.io.InputStream;
public class Resources {
// 根据配置文件的路径,将配置文件加载成字节输入流,存储在内存中
public static InputStream getResourceAsStream(String path) {
InputStream resourceAsStream = Resources.class.getClassLoader().getResourceAsStream(path);
return resourceAsStream;
}
}
package com.orm;
import com.orm.io.Resources;
import com.orm.sqlSession.SqlSession;
import com.orm.sqlSession.SqlSessionFactory;
import com.orm.sqlSession.SqlSessionFactoryBuilder;
import entity.User;
import org.dom4j.DocumentException;
import java.beans.PropertyVetoException;
import java.io.InputStream;
public class OrmTest {
public void test() throws PropertyVetoException, DocumentException {
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapepr.xml");
}
}
- 读取配置文件
* 读取配置文件,完成以后用 java bean 进行存储
* Configuration 存放数据库基本信息,Map<唯一标识,Mapper>,唯一标识 = namespace + “.”+ id
* MappedStatement 存放 sql 语句、statement 类型、输入参数 java 类型、输出参数 java 类型
5. 创建容器对象 MappedStatement 和 Configuration
package com.orm.pojo;
/**
* 容器对象
*/
public class MappedStatement {
// sql id
private String id;
// 返回值类型
private String resultType;
// 参数类型
private String paramterType;
// sql
private String 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 getParamterType() {
return paramterType;
}
public void setParamterType(String paramterType) {
this.paramterType = paramterType;
}
public String getSql() {
return sql;
}
public void setSql(String sql) {
this.sql = sql;
}
}
package com.orm.pojo;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
public class Configuration {
// 数据源对象
private DataSource dataSource;
/**
* key = statementId= sqlId+namespace sql的唯一标识
* value 就是封装好的 MappedStatement 对象
*/
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;
}
}
6. 解析核心配置文件和映射配置文件
- 创建 XMLConfigBuilder,用于解析核心配置文件
package com.orm.config;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.orm.io.Resources;
import com.orm.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();
}
/**
* 该方法将配置文件进行解析,封装Configuration的一个方法
*
* @param inputStream
* @return
*/
public Configuration parseConfig(InputStream inputStream) throws PropertyVetoException, DocumentException {
// 使用 dom4j 对配置文件进行解析
Document read = new SAXReader().read(inputStream);// 这个流就是父 sqlMapConfig.xml的解析
// Configuration
Element rootElement = read.getRootElement();
Properties properties = new Properties();
List<Element> list = rootElement.selectNodes("//property");
for (Element element : list) {
String name = element.attributeValue("name");
String value = element.attributeValue("value");
properties.setProperty(name, value);
}
// 创建c3p0 连接池
ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
comboPooledDataSource.setJdbcUrl((String) properties.get("jdbcUrl"));
comboPooledDataSource.setUser((String) properties.get("username"));
comboPooledDataSource.setPassword((String) properties.get("root"));
// jdbc 连接池对象 封装到 Configuration 对象
configuration.setDataSource(comboPooledDataSource);
// mapper.xml 解析
// 1. 拿到 Mapper.xml 的路径,将 mapper.xml解析成字节输入流
List<Element> mapperList = rootElement.selectNodes("//mapper");
for (Element element : mapperList) {
String mapperPath = element.attributeValue("//mapper");
// 根据路径,把配置文件加载成字节输入流
InputStream resourceAsStream = Resources.getResourceAsStream(mapperPath);
XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
xmlMapperBuilder.parse(resourceAsStream);
}
return null;
}
}
- 创建 XMLMapperBuilder,用于解析映射配置文件 mapper.xml
package com.orm.config;
import com.orm.pojo.Configuration;
import com.orm.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import sun.security.krb5.Config;
import java.io.InputStream;
import java.util.List;
public class XMLMapperBuilder {
private Configuration configuration;
public XMLMapperBuilder(Configuration config) {
this.configuration = config;
}
public void parse(InputStream inputStream) throws DocumentException {
// 拿到UserMapper的文档对象
Document document = new SAXReader().read(inputStream);
Element rootElement = document.getRootElement();
String namespace = rootElement.attributeValue("//namespace");
List<Element> selectNodes = rootElement.selectNodes("//select");
for (Element node : selectNodes) {
String id = node.attributeValue("//id");
String resultType = node.attributeValue("//resultType");
String parameterType = node.attributeValue("//parameterType");
String sqlText = node.getTextTrim();
// 封装到 MappedStatement 对象中
MappedStatement mappedStatement = new MappedStatement();
mappedStatement.setId(id);
mappedStatement.setResultType(resultType);
mappedStatement.setParamterType(parameterType);
mappedStatement.setSql(sqlText);
// 将 MapperedStatement封装到 Configuration 中 key=namespace+id value=
String key = namespace+"."+id;
configuration.getMappedStatementMap().put(key,mappedStatement);
}
}
}
7. 会话对象 SqlSession 类的定义
- 定义 SqlSession
package com.orm.sqlSession;
import java.util.List;
public interface SqlSession {
}
- 创建 DefaultSqlSession
package com.orm.sqlSession;
import com.orm.pojo.Configuration;
import com.orm.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;
}
}
- 创建 SessionFactory 接口
package com.orm.sqlSession;
public interface SqlSessionFactory {
public SqlSession opSession();
}
- 创建 SqlSessionFactoryBuilder
package com.orm.sqlSession;
import com.orm.config.XMLConfigBuilder;
import com.orm.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 {
// 1.使用 dom4j 解析配置文件,将解析出来的内容,封装到 Configuration 中
XMLConfigBuilder xmlConfigBuilder = new XMLConfigBuilder();
Configuration configuration = xmlConfigBuilder.parseConfig(inputStream);
// 2.创建 sqlSessionFactory 对象; 一个工厂类,主要职责就是生成 sqlSession 会话对象+工厂的设计模式
// 2.1 传入 configuration 对象
DefaultSqlSessionFactory defaultSqlSessionFactory = new DefaultSqlSessionFactory(configuration);
return defaultSqlSessionFactory;
}
}
- 创建 SqlSessionFactory 的时候,DefaultSqlSessionFactory,提供 openSession 方法
package com.orm.sqlSession;
import com.orm.pojo.Configuration;
import com.orm.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;
}
}
package com.orm.sqlSession;
import com.orm.pojo.Configuration;
public class DefaultSqlSessionFactory implements SqlSessionFactory{
private Configuration configuration; // 包含了数据库信息
public DefaultSqlSessionFactory(Configuration configuration) {
this.configuration = configuration;
}
@Override
public SqlSession opSession() {
return new DefaultSqlSession(configuration);
}
}
package com.orm;
import com.orm.io.Resources;
import com.orm.sqlSession.SqlSession;
import com.orm.sqlSession.SqlSessionFactory;
import com.orm.sqlSession.SqlSessionFactoryBuilder;
import entity.User;
import org.dom4j.DocumentException;
import java.beans.PropertyVetoException;
import java.io.InputStream;
public class OrmTest {
public void test() throws PropertyVetoException, DocumentException {
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapepr.xml");
// 获取 SqlSession
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.opSession();
}
}
8. 会话对象 SqlSession 方法的定义
- 添加查询所有和查询单个的方法
package com.orm.sqlSession;
import java.util.List;
public interface SqlSession {
// 查询所有,返回的集合类型不确定用泛型 E 表示
public <E>List<E> selectList(String statementId, Object ...params);
// 根据条件查询单个
public <T> T selectOne(String statementId, Object ...params);
}
- DefaultSqlSession 实现接口方法
package com.orm.sqlSession;
import com.orm.pojo.Configuration;
import com.orm.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) {
// 完成对 simpleExecutor 里的 query 方法调用
SimpleExecutor simpleExecutor = new SimpleExecutor();
MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
List<Object> list = null;
try {
list = simpleExecutor.query(configuration, mappedStatement, params);
} catch (Exception e) {
e.printStackTrace();
}
return (List<E>) list;
}
@Override
public <T> T selectOne(String statementId, Object... params) {
List<Object> objects = selectList(statementId, params);
if(objects.size() == 1){
return (T) objects.get(0);
}else {
throw new RuntimeException("查询结果为空或者返回结果过多");
}
}
}
- 创建 Executor
package com.orm.sqlSession;
import com.orm.pojo.Configuration;
import com.orm.pojo.MappedStatement;
import java.sql.SQLException;
import java.util.List;
public interface Executor {
// configuration 封装了数据库的配置信息,mappedStatement 封装了 SQL 的配置信息
public <E>List<E> query(Configuration configuration, MappedStatement mappedStatement,Object...params) throws SQLException, Exception;
}
- 创建 SimpleExecutor
package com.orm.sqlSession;
import com.orm.config.BoundSql;
import com.orm.pojo.Configuration;
import com.orm.pojo.MappedStatement;
import com.orm.utils.GenericTokenParser;
import com.orm.utils.ParameterMapping;
import com.orm.utils.ParameterMappingTokenHandler;
import com.orm.utils.TokenHandler;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.*;
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 语句
String sql = mappedStatement.getSql();
BoundSql boundSql = getBoundSql(sql);
// 3. 获取与处理对象 preparedStatement
PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());
// 4. 设置参数
List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
// 参数的全路径
String parameterType = mappedStatement.getResultType();
// 根据参数全路径拿到 Class 对象
Class<?> parameterTypeClass = getClassType(parameterType);
for (int i = 0; i < parameterMappingList.size(); i++) {
ParameterMapping parameterMapping = parameterMappingList.get(i);
String content = parameterMapping.getContent();//参数名称
// 反射
Field parameterTypeClassDeclaredField = parameterTypeClass.getDeclaredField(content);
// 设置下 暴力访问
parameterTypeClassDeclaredField.setAccessible(true);
// TODO
Object o = parameterTypeClassDeclaredField.get(params[0]);
preparedStatement.setObject(i+1,o);
}
// 5. 执行 sql
ResultSet resultSet = preparedStatement.executeQuery();
// 返回结果集对象的全路径
String resultType = mappedStatement.getResultType();
Class<?> resultTypeCass = getClassType(resultType);
Object instance = resultTypeCass.newInstance();
ArrayList<Object> objects = new ArrayList<>();
// 6. 封装结果集
while (resultSet.next()){
// 取出元数据,获取查询结果的字段名称
ResultSetMetaData metaData = resultSet.getMetaData();
for (int i = 1; i < metaData.getColumnCount(); i++) {//总列数
// 获取字段名称
String columnName = metaData.getColumnName(i);
// 根据列名,在resultSet 中获取到对应的字段值
// 字段值
Object fieldValue = resultSet.getObject(columnName);
// 使用反射或者内省,根据数据库表和实体的对应关系,完成封装
// PropertyDescriptor 是内省库中的一个类
PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName,resultTypeCass);
Method writeMethod = propertyDescriptor.getWriteMethod();
writeMethod.invoke(instance,fieldValue);
}
objects.add(instance);
}
return (List<E>) objects;
}
private Class<?> getClassType(String parameterType) throws ClassNotFoundException {
if(parameterType !=null){
Class<?> aClass = Class.forName(parameterType);
return aClass;
}
return null;
}
/**
* 完成对 #{} 的解析工作
* @param sql
* @return
*/
private BoundSql getBoundSql(String sql) {
// 1. 将 # {} 使用?进行代替
// 标记处理类,配置标记解析器来完成对占位符的
ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
// 解析出来的 SQL
String parsedSql = genericTokenParser.parse(sql);
// 2. 解析出#{} 中的值
// #{} 里面解析出来的参数名称
List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();
return new BoundSql(parsedSql, parameterMappings);
}
}
9. 查询对象 Query 定义
- 添加 utils,MyBatis 框架中封装的
/**
* 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.orm.utils;
/**
* @author Clinton Begin
*/
public interface TokenHandler {
String handleToken(String content);
}
package com.orm.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;
}
}
package com.orm.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;
}
}
/**
* 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.orm.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();
}
}
- 新建 BoundSql
package com.orm.config;
import com.orm.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.orm.sqlSession;
import com.orm.config.BoundSql;
import com.orm.pojo.Configuration;
import com.orm.pojo.MappedStatement;
import com.orm.utils.GenericTokenParser;
import com.orm.utils.ParameterMapping;
import com.orm.utils.ParameterMappingTokenHandler;
import com.orm.utils.TokenHandler;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.*;
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 语句
String sql = mappedStatement.getSql();
BoundSql boundSql = getBoundSql(sql);
// 3. 获取与处理对象 preparedStatement
PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());
// 4. 设置参数
/**
* 完成对 #{} 的解析工作
* @param sql
* @return
*/
private BoundSql getBoundSql(String sql) {
// 1. 将 # {} 使用?进行代替
// 标记处理类,配置标记解析器来完成对占位符的
ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
// 解析出来的 SQL
String parsedSql = genericTokenParser.parse(sql);
// 2. 解析出#{} 中的值
// #{} 里面解析出来的参数名称
List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();
return new BoundSql(parsedSql, parameterMappings);
}
}
10. 进行参数设置
package com.orm.sqlSession;
import com.orm.config.BoundSql;
import com.orm.pojo.Configuration;
import com.orm.pojo.MappedStatement;
import com.orm.utils.GenericTokenParser;
import com.orm.utils.ParameterMapping;
import com.orm.utils.ParameterMappingTokenHandler;
import com.orm.utils.TokenHandler;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.*;
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 语句
String sql = mappedStatement.getSql();
BoundSql boundSql = getBoundSql(sql);
// 3. 获取与处理对象 preparedStatement
PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());
// 4. 设置参数
List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
// 参数的全路径
String parameterType = mappedStatement.getResultType();
// 根据参数全路径拿到 Class 对象
Class<?> parameterTypeClass = getClassType(parameterType);
for (int i = 0; i < parameterMappingList.size(); i++) {
ParameterMapping parameterMapping = parameterMappingList.get(i);
String content = parameterMapping.getContent();//参数名称
// 反射
Field parameterTypeClassDeclaredField = parameterTypeClass.getDeclaredField(content);
// 设置下 暴力访问
parameterTypeClassDeclaredField.setAccessible(true);
// TODO
Object o = parameterTypeClassDeclaredField.get(params[0]);
preparedStatement.setObject(i+1,o);
}
// 5. 执行 sql
ResultSet resultSet = preparedStatement.executeQuery();
// 返回结果集对象的全路径
String resultType = mappedStatement.getResultType();
Class<?> resultTypeCass = getClassType(resultType);
Object instance = resultTypeCass.newInstance();
ArrayList<Object> objects = new ArrayList<>();
// 6. 封装结果集
while (resultSet.next()){
// 取出元数据,获取查询结果的字段名称
ResultSetMetaData metaData = resultSet.getMetaData();
for (int i = 1; i < metaData.getColumnCount(); i++) {//总列数
// 获取字段名称
String columnName = metaData.getColumnName(i);
// 根据列名,在resultSet 中获取到对应的字段值
// 字段值
Object fieldValue = resultSet.getObject(columnName);
// 使用反射或者内省,根据数据库表和实体的对应关系,完成封装
// PropertyDescriptor 是内省库中的一个类
PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName,resultTypeCass);
Method writeMethod = propertyDescriptor.getWriteMethod();
writeMethod.invoke(instance,fieldValue);
}
objects.add(instance);
}
return (List<E>) objects;
}
private Class<?> getClassType(String parameterType) throws ClassNotFoundException {
if(parameterType !=null){
Class<?> aClass = Class.forName(parameterType);
return aClass;
}
return null;
}
/**
* 完成对 #{} 的解析工作
* @param sql
* @return
*/
private BoundSql getBoundSql(String sql) {
// 1. 将 # {} 使用?进行代替
// 标记处理类,配置标记解析器来完成对占位符的
ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
// 解析出来的 SQL
String parsedSql = genericTokenParser.parse(sql);
// 2. 解析出#{} 中的值
// #{} 里面解析出来的参数名称
List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();
return new BoundSql(parsedSql, parameterMappings);
}
}
11. 封装返回结果集
package com.orm.sqlSession;
import com.orm.config.BoundSql;
import com.orm.pojo.Configuration;
import com.orm.pojo.MappedStatement;
import com.orm.utils.GenericTokenParser;
import com.orm.utils.ParameterMapping;
import com.orm.utils.ParameterMappingTokenHandler;
import com.orm.utils.TokenHandler;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.*;
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 语句
String sql = mappedStatement.getSql();
BoundSql boundSql = getBoundSql(sql);
// 3. 获取与处理对象 preparedStatement
PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());
// 4. 设置参数
List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
// 参数的全路径
String parameterType = mappedStatement.getResultType();
// 根据参数全路径拿到 Class 对象
Class<?> parameterTypeClass = getClassType(parameterType);
for (int i = 0; i < parameterMappingList.size(); i++) {
ParameterMapping parameterMapping = parameterMappingList.get(i);
String content = parameterMapping.getContent();//参数名称
// 反射
Field parameterTypeClassDeclaredField = parameterTypeClass.getDeclaredField(content);
// 设置下 暴力访问
parameterTypeClassDeclaredField.setAccessible(true);
// TODO
Object o = parameterTypeClassDeclaredField.get(params[0]);
preparedStatement.setObject(i+1,o);
}
// 5. 执行 sql
ResultSet resultSet = preparedStatement.executeQuery();
// 返回结果集对象的全路径
String resultType = mappedStatement.getResultType();
Class<?> resultTypeCass = getClassType(resultType);
Object instance = resultTypeCass.newInstance();
ArrayList<Object> objects = new ArrayList<>();
// 4. 封装结果集
while (resultSet.next()){
// 取出元数据,获取查询结果的字段名称
ResultSetMetaData metaData = resultSet.getMetaData();
for (int i = 1; i < metaData.getColumnCount(); i++) {//总列数
// 获取字段名称
String columnName = metaData.getColumnName(i);
// 根据列名,在resultSet 中获取到对应的字段值
// 字段值
Object fieldValue = resultSet.getObject(columnName);
// 使用反射或者内省,根据数据库表和实体的对应关系,完成封装
// PropertyDescriptor 是内省库中的一个类
PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName,resultTypeCass);
Method writeMethod = propertyDescriptor.getWriteMethod();
writeMethod.invoke(instance,fieldValue);
}
objects.add(instance);
}
return (List<E>) objects;
}
private Class<?> getClassType(String parameterType) throws ClassNotFoundException {
if(parameterType !=null){
Class<?> aClass = Class.forName(parameterType);
return aClass;
}
return null;
}
/**
* 完成对 #{} 的解析工作
* @param sql
* @return
*/
private BoundSql getBoundSql(String sql) {
// 1. 将 # {} 使用?进行代替
// 标记处理类,配置标记解析器来完成对占位符的
ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
// 解析出来的 SQL
String parsedSql = genericTokenParser.parse(sql);
// 2. 解析出#{} 中的值
// #{} 里面解析出来的参数名称
List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();
return new BoundSql(parsedSql, parameterMappings);
}
}
使用动态代理,实现 getMapper 方法
上面我们实现了基于传统 StatementId 模式的持久层框架。下面我们在使用端使用我们自己实现的持久层框架。
我们在 simpleormclient 中创建 IUserDao,如下图所示:
并在 IUserDao 中定义了两个方法。
package com.orm.test.dao;
import entity.User;
import java.util.List;
public interface IUserDao {
public List<User> findAll();
public User findByCondition(User user);
}
package com.orm.test.dao;
import com.orm.io.Resources;
import com.orm.sqlSession.SqlSession;
import com.orm.sqlSession.SqlSessionFactory;
import com.orm.sqlSession.SqlSessionFactoryBuilder;
import entity.User;
import java.io.InputStream;
import java.util.List;
public class IUserDaoImpl implements IUserDao{
public List<User> findAll() throws Exception{
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.opSession();
List<User> users = sqlSession.selectList("user.statementId");
for (User user : users) {
System.out.println(user);
}
return users;
}
public User findByCondition(User user) throws Exception {
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.opSession();
User selectOne = sqlSession.selectOne("user.statementId");
return selectOne;
}
}
问题分析
从代码中可以看出,在 Dao 层使用自定义持久层框架实现功能的时候,存在代码重复的问题:
- Dao 层每一个方法在实现的时候,存在代码重复,整个操作的过程模板重复(加载配置文件、创建 SqlSessionFactory、生成 SqlSession)
- 硬编码问题,statementId 在代码中硬编码了
解决思路
这些问题都存在 Dao 层的实现类,那么我们可不可以不用实现类?如果不用实现类也能完成对应方法的执行,就能解决存在的这两种问题。
所以我们的解决思路就是:使用代理模式生成 Dao 层接口的代理实现类。
实现
- SqlSession 添加 getMapper(...),为 Dao 层接口生成代理实现类。
package com.orm.sqlSession;
import java.util.List;
public interface SqlSession {
// 查询所有
public <E>List<E> selectList(String statementId, Object ...params);
// 根据条件查询单个
public <T> T selectOne(String statementId,Object ...params);
// 使用代理模式 生成 Dao 层的实现类
// 为 Dao 接口生成代理实现类
public <T> T getMapper(Class<?> mapperClass);
}
- DefaultSqlSession 实现类实现 getMapper
package com.orm.sqlSession;
import com.orm.pojo.Configuration;
import com.orm.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) {
// 完成对 simpleExecutor 里的 query 方法调用
SimpleExecutor simpleExecutor = new SimpleExecutor();
MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
List<Object> list = null;
try {
list = simpleExecutor.query(configuration, mappedStatement, params);
} catch (Exception e) {
e.printStackTrace();
}
return (List<E>) list;
}
@Override
public <T> T selectOne(String statementId, Object... params) {
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 动态代理生成代理对象,并返回
Object proxyInstance = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// proxy 是当前代理对象的引用
// method 是当前被调用方法的引用
// args 传递的参数
// 底层还是执行JDBC 代码,根据不同的情况去调用 selectList 和 selectOne
// 准备参数,1:statementId=namespace+id namespace.id = 接口全限定名.方法名
// 获取方法名
String methodName = method.getName();
// 获取接口的全限定名
String className = method.getDeclaringClass().getName();
String statementId = className+"."+methodName;
// 准备参数2:params = args
// 问题:我是调用 selectList 还是 selectOne?
// 获取被调用的返回值类型
Type genericReturnType = method.getGenericReturnType();
// 判断是否进行了泛型类型参数化
if(genericReturnType instanceof ParameterizedType){
List<Object> objects = selectList(statementId, args);
return objects;
}
return selectOne(statementId,args);
}
});
return (T) proxyInstance;
}
}
package com.orm.test;
import com.orm.sqlSession.SqlSession;
import com.orm.sqlSession.SqlSessionFactory;
import com.orm.sqlSession.SqlSessionFactoryBuilder;
import com.orm.test.dao.IUserDao;
import entity.User;
import java.io.InputStream;
import java.util.List;
public class Test {
public void test() throws Exception {
InputStream resourceAsStream = com.orm.io.Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.opSession();
IUserDao iUserDao = sqlSession.getMapper(IUserDao.class);
List<User> all = iUserDao.findAll();
}
}
- 完善动态代理逻辑。
@Override
public <T> T getMapper(Class<?> mapperClass) {
// 使用 JDK 动态代理生成代理对象,并返回
Object proxyInstance = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// proxy 是当前代理对象的引用
// method 是当前被调用方法的引用
// args 传递的参数
// 底层还是执行JDBC 代码,根据不同的情况去调用 selectList 和 selectOne
// 准备参数,1:statementId=namespace+id namespace.id = 接口全限定名.方法名
// 获取被调用方法的返回值类型、方法名
String methodName = method.getName();
// 获取接口的全限定名
String className = method.getDeclaringClass().getName();
String statementId = className+"."+methodName;
// 准备参数2:params = args
// 问题:我是调用 selectList 还是 selectOne?
// 获取被调用的返回值类型
Type genericReturnType = method.getGenericReturnType();
// 判断是否进行了泛型类型参数化
if(genericReturnType instanceof ParameterizedType){
List<Object> objects = selectList(statementId, args);
return objects;
}
return selectOne(statementId,args);
}
});
return (T) proxyInstance;
}
在写 invoke 方法前,我们都需要明白,不管我们如何分工和优化其底层都还是执行 JDBC。而执行 JDBC 的代码被我们封装在了 SimpleExecutor 的 query(...) 方法中。也就是说执行 JDBC 的时候我们需要调用该 query(...) 方法,这种感觉不妥。我们换种思路,不去直接调用该 query(...)。
怎么做呢?
我们可以根据不同情况去调用不同的方法,比如:我们调用 selectList 和 selectOne 这两个方法,而这两个方法都需要 statementId 和 params 作为入参。 所以我们需要准备 invoke 调用 JDBC 方法的入参,但是我们在 invoke 方法无法拿到 namespace 和 id 的,所以我们在 mapper.xml 文件中添加方法的时候 namespace 和 SQL 语句的 id 就不能随便写了。我们需要按照一定的规范来写。
- namespace 的值需要跟接口的全限定名称保持一致。
- Mapper 文件这 SQL 的 id 名称需要和接口中的方法名保持一致。
statementId 是 sql 语句的唯一标识,namespace.id = 接口全限定名.接口的方法名。