我们来自定义一个持久层框架,也就是Mybatis的简易版。

使用端的搭建

idea中新建maven工程IPersistence_test:



在resources目录下新建sqlMapConfig.xml文件,

  1. <Configuration>
  2. <dataSource>
  3. <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
  4. <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/lagou?useUnicode=true&amp;characterEncoding=utf8&amp;zeroDateTimeBehavior=convertToNull&amp;useSSL=false"></property>
  5. <property name="user" value="root"></property>
  6. <property name="password" value="000"></property>
  7. </dataSource>
  8. <mapper resource="UserMapper.xml"></mapper>
  9. </Configuration>

UserMapper.xml:

  1. <mapper namespace="user">
  2. <select id="selectOne" paramterType="com.lagou.pojo.User"
  3. resultType="com.lagou.pojo.User">
  4. select * from user where id = #{id} and username =#{username}
  5. </select>
  6. <select id="selectList" resultType="com.lagou.pojo.User">
  7. select * from user
  8. </select>
  9. </mapper>

User实体类:

  1. package com.lagou.test;
  2. /**
  3. * @author liuyj
  4. * @Title: User
  5. * @create 2020-05-29 15:06
  6. * @ProjectName lagou_project
  7. * @Description: TODO
  8. */
  9. public class User {
  10. private Integer id;
  11. private String username;
  12. public Integer getId() {
  13. return id;
  14. }
  15. public void setId(Integer id) {
  16. this.id = id;
  17. }
  18. public String getUsername() {
  19. return username;
  20. }
  21. public void setUsername(String username) {
  22. this.username = username;
  23. }
  24. @Override
  25. public String toString() {
  26. return "User{" +
  27. "id=" + id +
  28. ", username='" + username + '\'' +
  29. '}';
  30. }
  31. }

使用端暂时就搭建完成。

持久层框架端的搭建

下面我们来搭建持久层框架:

新建一个module,maven项目:IPersistence

pom.xml中引入一下依赖

  1. <dependencies>
  2. <dependency>
  3. <groupId>mysql</groupId>
  4. <artifactId>mysql-connector-java</artifactId>
  5. <version>5.1.44</version>
  6. </dependency>
  7. <!-- 连接池-->
  8. <dependency>
  9. <groupId>c3p0</groupId>
  10. <artifactId>c3p0</artifactId>
  11. <version>0.9.1.2</version>
  12. </dependency>
  13. <dependency>
  14. <groupId>log4j</groupId>
  15. <artifactId>log4j</artifactId>
  16. <version>1.2.12</version>
  17. </dependency>
  18. <dependency>
  19. <groupId>junit</groupId>
  20. <artifactId>junit</artifactId>
  21. <version>4.10</version>
  22. </dependency>
  23. <!-- 解析xml文件-->
  24. <dependency>
  25. <groupId>dom4j</groupId>
  26. <artifactId>dom4j</artifactId>
  27. <version>1.6.1</version>
  28. </dependency>
  29. <dependency>
  30. <groupId>jaxen</groupId>
  31. <artifactId>jaxen</artifactId>
  32. <version>1.1.6</version>
  33. </dependency>
  34. </dependencies>

创建一个Configuration类,主要是存放从sqlMapConfig.xml和Usermapper.xml配置文件中解析出来的一些元素和内容,用来一层层向下传递:

  1. package com.lagou.pojo;
  2. import javax.sql.DataSource;
  3. import java.util.HashMap;
  4. import java.util.Map;
  5. /**
  6. * @author liuyj
  7. * @Title: Configuration
  8. * @create 2020-05-27 15:20
  9. * @ProjectName IPersistence
  10. * @Description: 存放sqlMapConfig.xml解析出来的内容
  11. */
  12. public class Configuration {
  13. //存放数据库配置信息,从sqlMapConfig.xml中解析出来
  14. private DataSource dataSource;
  15. //存放Mapper.xml中解析出来的内容,key是statementId
  16. private Map<String,MappedStatement> mappedStatementMap=new HashMap<String, MappedStatement>();
  17. public DataSource getDataSource() {
  18. return dataSource;
  19. }
  20. public void setDataSource(DataSource dataSource) {
  21. this.dataSource = dataSource;
  22. }
  23. public Map<String, MappedStatement> getMappedStatementMap() {
  24. return mappedStatementMap;
  25. }
  26. public void setMappedStatementMap(Map<String, MappedStatement> mappedStatementMap) {
  27. this.mappedStatementMap = mappedStatementMap;
  28. }
  29. }

其中DataSource 封装的是数据库信息,Configuration中封装了一个对象MappedStatement:

  1. package com.lagou.pojo;
  2. /**
  3. * @author liuyj
  4. * @Title: MappedStatement
  5. * @create 2020-05-27 15:13
  6. * @ProjectName IPersistence
  7. * @Description: 存放UserMapper.xml解析出来的内容
  8. */
  9. public class MappedStatement {
  10. //id标识
  11. private String id;
  12. //返回值类型
  13. private String resultType;
  14. //传入参数类型
  15. private String paramenterType;
  16. //sql
  17. private String sql;
  18. public String getId() {
  19. return id;
  20. }
  21. public void setId(String id) {
  22. this.id = id;
  23. }
  24. public String getResultType() {
  25. return resultType;
  26. }
  27. public void setResultType(String resultType) {
  28. this.resultType = resultType;
  29. }
  30. public String getParamenterType() {
  31. return paramenterType;
  32. }
  33. public void setParamenterType(String paramenterType) {
  34. this.paramenterType = paramenterType;
  35. }
  36. public String getSql() {
  37. return sql;
  38. }
  39. public void setSql(String sql) {
  40. this.sql = sql;
  41. }
  42. }

主要是用来存储从映射配置文件中解析出来的sql查询标签的id及传入参数、返回结果类型、查询的sql等,其中Mapper.xml中每一个标签,

比如:

  1. <select id="selectList" resultType="com.lagou.pojo.User">
  2. select * from user
  3. </select>

都会封装成一个MappedStatement对象,然后所有的MappedStatement对象都被存储到Configuration类中的Map集合mappedStatementMap当中去,Map集合中的key是statementId(statementId由两部分组成,一是Mapper.xml中的namespace,二是每一个标签中的id,比如UserMapper.xml中的selectOne,在Configuration中map集合中的key值就是user.selectOne)。

Resource文件:

主要用来读取xml文件,作为一个字节流存储在内存中:

  1. package com.lagou.io;
  2. import java.io.InputStream;
  3. /**
  4. * @author liuyj
  5. * @Title:
  6. * @create 2020-05-27 14:48
  7. * @ProjectName IPersistence
  8. * @Description: TODO
  9. */
  10. public class Resources {
  11. //根据配置文件的路径,将配置文件加载成字节输入流,存储在内存中
  12. public static InputStream getResourceAsStream(String path){
  13. InputStream resourceStream= Resources.class.getClassLoader().getResourceAsStream(path);
  14. return resourceStream;
  15. }
  16. }

SqlSessionFactoryBuilder:

  1. package com.lagou.sqlSession;
  2. import com.lagou.config.XMLConfigBuilder;
  3. import com.lagou.pojo.Configuration;
  4. import org.dom4j.DocumentException;
  5. import java.beans.PropertyVetoException;
  6. import java.io.InputStream;
  7. /**
  8. * @author liuyj
  9. * @Title: SqlSessionFactoryBuilder
  10. * @create 2020-05-27 15:37
  11. * @ProjectName IPersistence
  12. * @Description: TODO
  13. */
  14. public class SqlSessionFactoryBuilder {
  15. public SqlSessionFactory build(InputStream in) throws DocumentException, PropertyVetoException {
  16. //第一,使用dom4j解析配置文件,将解析出来的内容封装到configuration中
  17. XMLConfigBuilder xmlConfigBuilder=new XMLConfigBuilder();
  18. Configuration configuration = xmlConfigBuilder.parseConfig(in);
  19. //第二:创建sqlSessionFactory对象:工厂类:生产sqlSession:会话对象
  20. DefaultSqlSessionFactory defaultSqlSessionFactory=new DefaultSqlSessionFactory(configuration);
  21. return defaultSqlSessionFactory;
  22. }
  23. }

XMLConfigBuilder :

使用dom4j解析sqlMapConfig.xml文件,并调用XMLMapperBuilder 中的方法解析Mapper.xml映射文件,将结果封装在Configuration对象中:

  1. package com.lagou.config;
  2. import com.lagou.io.Resources;
  3. import com.lagou.pojo.Configuration;
  4. import com.mchange.v2.c3p0.ComboPooledDataSource;
  5. import org.dom4j.Document;
  6. import org.dom4j.DocumentException;
  7. import org.dom4j.Element;
  8. import org.dom4j.io.SAXReader;
  9. import java.beans.PropertyVetoException;
  10. import java.io.InputStream;
  11. import java.util.List;
  12. import java.util.Properties;
  13. /**
  14. * @author liuyj
  15. * @Title: XMLConfigBuilder
  16. * @create 2020-05-27 15:39
  17. * @ProjectName IPersistence
  18. * @Description: TODO
  19. */
  20. public class XMLConfigBuilder {
  21. private Configuration configuration;
  22. public XMLConfigBuilder(){
  23. this.configuration=new Configuration();
  24. }
  25. /**
  26. *
  27. *该方法就是使用dom4j将配置文件解析,封装为Configuration
  28. */
  29. public Configuration parseConfig(InputStream inputStream) throws DocumentException, PropertyVetoException {
  30. Document document = new SAXReader().read(inputStream);
  31. //<Configuration>标签
  32. Element rootElement = document.getRootElement();
  33. List<Element> list = rootElement.selectNodes("//property");
  34. Properties properties=new Properties();
  35. for (Element element : list) {
  36. String name = element.attributeValue("name");
  37. String value = element.attributeValue("value");
  38. properties.setProperty(name,value);
  39. }
  40. ComboPooledDataSource comboPooledDataSource=new ComboPooledDataSource();
  41. comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
  42. comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
  43. comboPooledDataSource.setUser(properties.getProperty("user"));
  44. comboPooledDataSource.setPassword(properties.getProperty("password"));
  45. configuration.setDataSource(comboPooledDataSource);
  46. //解析sqlMapConfig.xml里面的mapper标签,
  47. // 解析mapper.xml:拿到路径--字节输入流--dom4j解析
  48. List<Element> mapperList = rootElement.selectNodes("//mapper");
  49. for (Element element : mapperList) {
  50. String mapperPath = element.attributeValue("resource");
  51. InputStream resourceAsStream = Resources.getResourceAsStream(mapperPath);
  52. XMLMapperBuilder xmlMaperBuilder=new XMLMapperBuilder(configuration);
  53. xmlMaperBuilder.parse(resourceAsStream);
  54. }
  55. return configuration;
  56. }
  57. }

XMLMapperBuilder :

用来解析映射配置文件Mapper.xml中的内容:

  1. package com.lagou.config;
  2. import com.lagou.pojo.Configuration;
  3. import com.lagou.pojo.MappedStatement;
  4. import org.dom4j.Document;
  5. import org.dom4j.DocumentException;
  6. import org.dom4j.Element;
  7. import org.dom4j.io.SAXReader;
  8. import java.io.InputStream;
  9. import java.util.List;
  10. /**
  11. * @author liuyj
  12. * @Title: XMLMapperBuilder
  13. * @create 2020-05-28 10:59
  14. * @ProjectName lagou_project
  15. * @Description: 解析mapper.xml文件
  16. */
  17. public class XMLMapperBuilder {
  18. private Configuration configuration;
  19. public XMLMapperBuilder(Configuration configuration) {
  20. this.configuration=configuration;
  21. }
  22. public void parse(InputStream inputStream) throws DocumentException {
  23. Document document = new SAXReader().read(inputStream);
  24. Element rootElement = document.getRootElement();
  25. String namespace = rootElement.attributeValue("namespace");
  26. List<Element> list = rootElement.selectNodes("//select");
  27. for (Element element : list) {
  28. String id = element.attributeValue("id");
  29. String parameterType = element.attributeValue("parameterType");
  30. String resultType = element.attributeValue("resultType");
  31. String sqlText = element.getTextTrim();
  32. String key=namespace+"."+id;
  33. MappedStatement mappedStatement=new MappedStatement();
  34. mappedStatement.setId(id);
  35. mappedStatement.setParamenterType(parameterType);
  36. mappedStatement.setResultType(resultType);
  37. mappedStatement.setSql(sqlText);
  38. configuration.getMappedStatementMap().put(key,mappedStatement);
  39. }
  40. }
  41. }
  1. package com.lagou.sqlSession;
  2. /**
  3. * @author liuyj
  4. * @Title: SqlSessionFactory
  5. * @create 2020-05-27 15:38
  6. * @ProjectName IPersistence
  7. * @Description: TODO
  8. */
  9. public interface SqlSessionFactory {
  10. SqlSession openSession();
  11. }
  1. package com.lagou.sqlSession;
  2. import com.lagou.pojo.Configuration;
  3. /**
  4. * @author liuyj
  5. * @Title: DefaultSqlSessionFactory
  6. * @create 2020-05-28 11:38
  7. * @ProjectName lagou_project
  8. * @Description: TODO
  9. */
  10. public class DefaultSqlSessionFactory implements SqlSessionFactory{
  11. private Configuration configuration;
  12. public DefaultSqlSessionFactory(Configuration configuration) {
  13. this.configuration = configuration;
  14. }
  15. public SqlSession openSession() {
  16. return new DefaultSqlSession(configuration);
  17. }
  18. }

SqlSession及实现类DefaultSqlSession:

  1. package com.lagou.sqlSession;
  2. import java.util.List;
  3. /**
  4. * @author liuyj
  5. * @Title: SqlSession
  6. * @create 2020-05-28 11:56
  7. * @ProjectName lagou_project
  8. * @Description: TODO
  9. */
  10. public interface SqlSession {
  11. //查询所有
  12. public <E> List<E> selectList(String statementid, Object... params) throws Exception;
  13. //根据条件查询单个
  14. public <T> T selectOne(String statementid,Object... params) throws Exception;
  15. }
  1. package com.lagou.sqlSession;
  2. import com.lagou.pojo.Configuration;
  3. import com.lagou.pojo.MappedStatement;
  4. import java.lang.reflect.*;
  5. import java.util.List;
  6. /**
  7. * @author liuyj
  8. * @Title: DefaultSqlSession
  9. * @create 2020-05-28 11:57
  10. * @ProjectName lagou_project
  11. * @Description: TODO
  12. */
  13. public class DefaultSqlSession implements SqlSession {
  14. private Configuration configuration;
  15. public DefaultSqlSession(Configuration configuration) {
  16. this.configuration = configuration;
  17. }
  18. public <E> List<E> selectList(String statementid, Object... params) throws Exception {
  19. //将要去完成对simpleExecutor里的query方法的调用
  20. SimpleExecutor simpleExecutor = new SimpleExecutor();
  21. MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementid);
  22. List<Object> list = simpleExecutor.query(configuration, mappedStatement, params);
  23. return (List<E>) list;
  24. }
  25. public <T> T selectOne(String statementid, Object... params) throws Exception {
  26. List<Object> objects = selectList(statementid, params);
  27. if(objects.size()==1){
  28. return (T) objects.get(0);
  29. }else {
  30. throw new RuntimeException("查询结果为空或者返回结果过多");
  31. }
  32. }
  33. }

SqlSession实现类中调用的Executor及其实现类SimpleExecutor :

  1. package com.lagou.sqlSession;
  2. import com.lagou.pojo.Configuration;
  3. import com.lagou.pojo.MappedStatement;
  4. import java.util.List;
  5. /**
  6. * @author lyj
  7. * @Title: Executor
  8. * @ProjectName lagou_project
  9. * @Description: TODO
  10. * @date 2020/5/28 22:00
  11. */
  12. public interface Executor {
  13. public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception;
  14. }

package com.lagou.sqlSession;

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.*;

import java.util.ArrayList;

import java.util.List;

/**

  • @author lyj
  • @Title: SimpleExecutor
  • @ProjectName lagou_project
  • @Description: TODO
  • @date 2020/5/28 21:59

    */

public class SimpleExecutor implements Executor {

  1. public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
  2. //注册驱动,获取数据库连接
  3. Connection connection = configuration.getDataSource().getConnection();
  4. //获取sql语句:select * from user where id=#{id} and username=#{username}
  5. //转换sql:select * from user where id=? and username=?,同时需要对#{}里面的值进行解析存储
  6. String sql = mappedStatement.getSql();
  7. BoundSql boundSql=getBoundSql(sql);
  8. //获取预处理对象preparedStatement
  9. PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());
  10. //设置参数
  11. //获取到了参数的全路径
  12. String paramenterType = mappedStatement.getParamenterType();
  13. Class<?> parametertypeClass=getClassType(paramenterType);
  14. List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
  15. for (int i = 0; i < parameterMappingList.size(); i++) {
  16. ParameterMapping parameterMapping = parameterMappingList.get(i);
  17. String content = parameterMapping.getContent();
  18. //反射
  19. Field declaredField = parametertypeClass.getDeclaredField(content);
  20. //暴力访问
  21. declaredField.setAccessible(true);
  22. Object o = declaredField.get(params[0]);
  23. preparedStatement.setObject(i+1,o);
  24. }
  25. //执行sql
  26. ResultSet resultSet = preparedStatement.executeQuery();
  27. String resultType = mappedStatement.getResultType();
  28. Class<?> resultTypeClass = getClassType(resultType);
  29. ArrayList<Object> objects = new ArrayList<Object>();
  30. //封装返回结果集
  31. while (resultSet.next()) {
  32. Object o = resultTypeClass.newInstance();
  33. //元数据
  34. ResultSetMetaData metaData = resultSet.getMetaData();
  35. for (int i = 1; i <= metaData.getColumnCount(); i++) {
  36. //字段名
  37. String columnName = metaData.getColumnName(i);
  38. //字段值
  39. Object value = resultSet.getObject(columnName);
  40. //使用反射或者内省,根据数据库表和实体的对应关系,完成封装
  41. PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultTypeClass);
  42. Method writeMethod = propertyDescriptor.getWriteMethod();
  43. writeMethod.invoke(o,value);
  44. }
  45. objects.add(o);
  46. }
  47. return (List<E>) objects;
  48. }
  49. /**
  50. * 完成对#{}的解析工作:1.将#{}使用?代替 ,2.解析出#{}里面的值进行存储
  51. * @param sql
  52. * @return
  53. */
  54. private BoundSql getBoundSql(String sql) {
  55. //标记处理类:配置标记解析器GenericTokenParser来完成对配置文件的解析工作,其中TokenHandler主要完成处理
  56. ParameterMappingTokenHandler parameterMappingTokenHandler=new ParameterMappingTokenHandler();

//GenericTokenParser:通用的标记解析器,完成了对代码中占位符的解析,然后再根据给定的标记处理器(TokenHandler)来进行表达式的处理

//三个参数:分别为openToken(开始标记)、closeToken(结束标记)、handler(标记处理器)

  1. GenericTokenParser genericTokenParser=new GenericTokenParser("#{","}",parameterMappingTokenHandler);
  2. //解析出来的sql
  3. String parseSql = genericTokenParser.parse(sql);
  4. //从#{}里面解析出来的参数名称
  5. List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();
  6. BoundSql boundSql=new BoundSql(parseSql,parameterMappings);
  7. return boundSql;
  8. }
  9. }
  10. ```

BoundSql

```java

package com.lagou.sqlSession;

import com.lagou.utils.ParameterMapping;

import java.util.ArrayList;

import java.util.List;

/**

  • @author lyj
  • @Title: BoundSql
  • @ProjectName lagou_project
  • @Description: TODO
  • @date 2020/5/28 22:03

    */

public class BoundSql {

private String sqlText;

private ListparameterMappingList=new ArrayList();

  1. public BoundSql(String sqlText, List<ParameterMapping> parameterMappingList) {
  2. this.sqlText = sqlText;
  3. this.parameterMappingList = parameterMappingList;
  4. }
  5. public String getSqlText() {
  6. return sqlText;
  7. }
  8. public void setSqlText(String sqlText) {
  9. this.sqlText = sqlText;
  10. }
  11. public List<ParameterMapping> getParameterMappingList() {
  12. return parameterMappingList;
  13. }
  14. public void setParameterMappingList(List<ParameterMapping> parameterMappingList) {
  15. this.parameterMappingList = parameterMappingList;
  16. }

}


  1. SimpleExecutor 中使用的几个标记解析器,也附录一下吧,是从mybatis源码中直接拿来用的:
  2. GenericTokenParser
  3. ```java
  4. /**
  5. * Copyright 2009-2017 the original author or authors.
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. */
  19. package com.lagou.utils;
  20. /**
  21. * @author Clinton Begin
  22. */
  23. public class GenericTokenParser {
  24. private final String openToken; //开始标记
  25. private final String closeToken; //结束标记
  26. private final TokenHandler handler; //标记处理器
  27. public GenericTokenParser(String openToken, String closeToken, TokenHandler handler) {
  28. this.openToken = openToken;
  29. this.closeToken = closeToken;
  30. this.handler = handler;
  31. }
  32. /**
  33. * 解析${}和#{}
  34. * @param text
  35. * @return
  36. * 该方法主要实现了配置文件、脚本等片段中占位符的解析、处理工作,并返回最终需要的数据。
  37. * 其中,解析工作由该方法完成,处理工作是由处理器handler的handleToken()方法来实现
  38. */
  39. public String parse(String text) {
  40. // 验证参数问题,如果是null,就返回空字符串。
  41. if (text == null || text.length()==0) {
  42. return "";
  43. }
  44. // 下面继续验证是否包含开始标签,如果不包含,默认不是占位符,直接原样返回即可,否则继续执行。
  45. int start = text.indexOf(openToken, 0);
  46. if (start == -1) {
  47. return text;
  48. }
  49. // 把text转成字符数组src,并且定义默认偏移量offset=0、存储最终需要返回字符串的变量builder,
  50. // text变量中占位符对应的变量名expression。判断start是否大于-1(即text中是否存在openToken),如果存在就执行下面代码
  51. char[] src = text.toCharArray();
  52. int offset = 0;
  53. final StringBuilder builder = new StringBuilder();
  54. StringBuilder expression = null;
  55. while (start > -1) {
  56. // 判断如果开始标记前如果有转义字符,就不作为openToken进行处理,否则继续处理
  57. if (start > 0 && src[start - 1] == '\\') {
  58. builder.append(src, offset, start - offset - 1).append(openToken);
  59. offset = start + openToken.length();
  60. } else {
  61. //重置expression变量,避免空指针或者老数据干扰。
  62. if (expression == null) {
  63. expression = new StringBuilder();
  64. } else {
  65. expression.setLength(0);
  66. }
  67. builder.append(src, offset, start - offset);
  68. offset = start + openToken.length();
  69. int end = text.indexOf(closeToken, offset);
  70. while (end > -1) {////存在结束标记时
  71. if (end > offset && src[end - 1] == '\\') {//如果结束标记前面有转义字符时
  72. // this close token is escaped. remove the backslash and continue.
  73. expression.append(src, offset, end - offset - 1).append(closeToken);
  74. offset = end + closeToken.length();
  75. end = text.indexOf(closeToken, offset);
  76. } else {//不存在转义字符,即需要作为参数进行处理
  77. expression.append(src, offset, end - offset);
  78. offset = end + closeToken.length();
  79. break;
  80. }
  81. }
  82. if (end == -1) {
  83. // close token was not found.
  84. builder.append(src, start, src.length - start);
  85. offset = src.length;
  86. } else {
  87. //首先根据参数的key(即expression)进行参数处理,返回?作为占位符
  88. builder.append(handler.handleToken(expression.toString()));
  89. offset = end + closeToken.length();
  90. }
  91. }
  92. start = text.indexOf(openToken, offset);
  93. }
  94. if (offset < src.length) {
  95. builder.append(src, offset, src.length - offset);
  96. }
  97. return builder.toString();
  98. }
  99. }

ParameterMapping:

  1. package com.lagou.utils;
  2. public class ParameterMapping {
  3. private String content;
  4. public ParameterMapping(String content) {
  5. this.content = content;
  6. }
  7. public String getContent() {
  8. return content;
  9. }
  10. public void setContent(String content) {
  11. this.content = content;
  12. }
  13. }

ParameterMappingTokenHandler:

  1. package com.lagou.utils;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. public class ParameterMappingTokenHandler implements TokenHandler {
  5. private List<ParameterMapping> parameterMappings = new ArrayList<ParameterMapping>();
  6. // context是参数名称 #{id} #{username}
  7. public String handleToken(String content) {
  8. parameterMappings.add(buildParameterMapping(content));
  9. return "?";
  10. }
  11. private ParameterMapping buildParameterMapping(String content) {
  12. ParameterMapping parameterMapping = new ParameterMapping(content);
  13. return parameterMapping;
  14. }
  15. public List<ParameterMapping> getParameterMappings() {
  16. return parameterMappings;
  17. }
  18. public void setParameterMappings(List<ParameterMapping> parameterMappings) {
  19. this.parameterMappings = parameterMappings;
  20. }
  21. }

  1. package com.lagou.utils;
  2. /**
  3. * @author Clinton Begin
  4. */
  5. public interface TokenHandler {
  6. String handleToken(String content);
  7. }

测试使用:

先生成jar包,执行mvn install命令。

mvn install



在使用端IPersistence_test中引入jar包:

  1. <dependency>
  2. <groupId>com.lagou</groupId>
  3. <artifactId>IPersistence</artifactId>
  4. <version>1.0-SNAPSHOT</version>
  5. </dependency>

数据库建表:



测试:


  1. package com.lagou.test;
  2. import com.lagou.dao.IUserDao;
  3. import com.lagou.io.Resources;
  4. import com.lagou.sqlSession.SqlSession;
  5. import com.lagou.sqlSession.SqlSessionFactory;
  6. import com.lagou.sqlSession.SqlSessionFactoryBuilder;
  7. import org.dom4j.DocumentException;
  8. import org.junit.Before;
  9. import org.junit.Test;
  10. import java.beans.PropertyVetoException;
  11. import java.io.InputStream;
  12. /**
  13. * @author liuyj
  14. * @Title: IPersistenctTest
  15. * @create 2020-05-27 15:08
  16. * @ProjectName IPersistence
  17. * @Description: TODO
  18. */
  19. public class IPersistenctTest {
  20. private SqlSession sqlSession;
  21. @Before
  22. public void before() throws PropertyVetoException, DocumentException {
  23. InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
  24. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
  25. sqlSession = sqlSessionFactory.openSession();
  26. }
  27. @Test
  28. public void test() throws Exception {
  29. //调用
  30. User user=new User();
  31. user.setId(1);
  32. user.setUsername("张三");
  33. User user2 = sqlSession.selectOne("user.selectOne", user);
  34. System.out.println(user2);
  35. }
  36. }

运行结果:



大功告成。

下节我们来讲对于我们这个框架的一个优化。

深入理解Mybatis(第一讲)——手写ORM框架(简易版Mybatis)的更多相关文章

  1. 重学 Java 设计模式:实战中介者模式「按照Mybaits原理手写ORM框架,给JDBC方式操作数据库增加中介者场景」

    作者:小傅哥 博客:https://bugstack.cn - 原创系列专题文章 沉淀.分享.成长,让自己和他人都能有所收获! 一.前言 同龄人的差距是从什么时候拉开的 同样的幼儿园.同样的小学.一样 ...

  2. 基于springJDBC手写ORM框架

    一.添加MySQLjar包依赖 二.结构 三.文件内容 (一).bean包 1.ColumnInfo.java 2.javaFiledInfo.java 3.TableInfo.java 4.Conf ...

  3. 手写Spring框架,加深对Spring工作机制的理解!

    在我们的日常工作中,经常会用到Spring.Spring Boot.Spring Cloud.Struts.Mybatis.Hibernate等开源框架,有了这些框架的诞生,平时的开发工作量也是变得越 ...

  4. 要想精通Mybatis?从手写Mybatis框架开始吧!

    1.Mybatis组成 动态SQL Config配置 Mapper配置 2.核心源码分析 Configuration源码解析 SqlSessionFactory源码解析 SqlSession源码解析 ...

  5. 第一个手写Win32窗口程序

    第一个手写Win32窗口程序 一 Windows编程基础 1 Win32应用程序的基本类型 1.1 控制台程序 不需要完善的Windows窗口,可以使用DOS窗口 的方式显示. 1.2 Win32窗口 ...

  6. 手写DAO框架(一)-从“1”开始

    背景: 很久(4年)之前写了一个DAO框架-zxdata(https://github.com/shuimutong/zxdata),这是我写的第一个框架.因为没有使用文档,我现在如果要用的话,得从头 ...

  7. Spring 08: AOP面向切面编程 + 手写AOP框架

    核心解读 AOP:Aspect Oriented Programming,面向切面编程 核心1:将公共的,通用的,重复的代码单独开发,在需要时反织回去 核心2:面向接口编程,即设置接口类型的变量,传入 ...

  8. 手写一套迷你版HTTP服务器

    本文主要介绍如何通过netty来手写一套简单版的HTTP服务器,同时将关于netty的许多细小知识点进行了串联,用于巩固和提升对于netty框架的掌握程度. 服务器运行效果 服务器支持对静态文件css ...

  9. 手写DAO框架(二)-开发前的最后准备

    -------前篇:手写DAO框架(一)-从“1”开始 --------- 前言:前篇主要介绍了写此框架的动机,把主要功能点大致介绍了一下.此篇文章主要介绍开发前最后的一些准备.主要包括一些基础知识点 ...

随机推荐

  1. 威联通(NAS)应用篇:自建OwnCloud网盘(百度网盘,拜拜~~~)

    基础环境: 威联通一台 已安装好 ContainerStation 公网 IP(非必须) 自有公网域名 下载镜像文件 提醒:建议先把威联通的自带镜像源改为国内的阿里云镜像源,教程:https://ww ...

  2. 使用kubeadm部署k8s集群[v1.18.0]

    使用kubeadm部署k8s集群 环境 IP地址 主机名 节点 10.0.0.63 k8s-master1 master1 10.0.0.63 k8s-master2 master2 10.0.0.6 ...

  3. P1750 出栈序列

    这好像是普及难度的吧~ 感觉再次被小学生吊打了........ \(\color{Red}{----------------------=|(●'◡'●)|=我是手动的分割线------------- ...

  4. Tomcat服务器的下载与安装,修改端口号

    安装及简单配置Tomcat服务器: 1.登录www.apache.org 网站,之后点击Projects , 点击Project List,找到Tomcat. 2.点击Tomcat之后,之后进入Tom ...

  5. 聊聊 TypeScript 中的类型保护

    聊聊 TypeScript 中的类型保护 在 TypeScript 中使用联合类型时,往往会碰到这种尴尬的情况: interface Bird { // 独有方法 fly(); // 共有方法 lay ...

  6. Web_php_include

    0x01 函数分析 <?php show_source(__FILE__); echo $_GET['hello']; $page=$_GET['page']; while (strstr($p ...

  7. P3366【模板】最小生成树

    P3366[模板]最小生成树 Kruskal #include <bits/stdc++.h> using namespace std; typedef long long ll; ; ; ...

  8. mysql小白系列_06 备份与恢复

    1.使用mydumper工具全库备份. 1)源码编译安装 2)全库备份 2.误操作truncate table gyj_t1;利用mysqldump的备份和binlog日志对表gyj_t1做完全恢复. ...

  9. UVALive8518 Sum of xor sum

    题目链接:https://vjudge.net/problem/UVALive-8518 题目大意: 给定一个长度为 $N$ 的数字序列 $A$,进行 $Q$ 次询问,每次询问 $[L,R]$,需要回 ...

  10. ShoneSharp语言(S#)软件更新13.7版

    ShoneSharp语言(S#)编辑解析运行器 软件更新13.7版 作者:Shone 近期在写博客过程中对S#进行增强,把语法规则更新到2.0版,并同步更新软件到ShoneSharp.13.7.exe ...