简单实现自定义持久层框架,手写MyBatis实现基础功能

Posted 丿涛哥哥

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了简单实现自定义持久层框架,手写MyBatis实现基础功能相关的知识,希望对你有一定的参考价值。

简单实现自定义持久层框架,手写MyBatis实现基础功能

源码请点击–>手写持久层框架源码

1、 分析JDBC操作问题

public static void main(String[] args) {
    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();
		// 遍历查询结果集
		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问题总结:

原始jdbc开发存在的问题如下:

  1. 数据库连接创建、释放频繁造成系统资源浪费,从而影响系统性能。
  2. Sql语句在代码中硬编码,造成代码不易维护,实际应用中sql变化的可能较大,sql变动需要改变 java代码。
  3. 使用preparedStatement向占有位符号传参数存在硬编码,因为sql语句的where条件不一定,可能多也可能少,修改sql还要修改代码,系统不易维护。
  4. 对结果集解析存在硬编码(查询列名),sql变化导致解析代码变化,系统不易维护,如果能将数据库记录封装成pojo对象解析比较方便。

2、 问题解决思路

  1. 使用数据库连接池初始化连接资源
  2. 将sql语句抽取到xml配置文件中
  3. 使用反射、内省等底层技术,自动将实体与表进行属性与字段的自动映射

3、 自定义框架设计

使用端:

提供核心配置文件:

sqlMapConfig.xml : 存放数据源信息,引入mapper.xml

Mapper.xml : sql语句的配置文件信息

框架端:

1、读取配置文件

读取完成以后以流的形式存在,我们不能将读取到的配置信息以流的形式存放在内存中,不好操作,可以创建javaBean来存储

Configuration : 存放数据库基本信息、Map<唯一标识,Mapper> 唯一标识:namespace + “.” + id

MappedStatement:sql语句、statement类型、输入参数java类型、输出参数java类型

2、解析配置文件

创建sqlSessionFactoryBuilder类:

方法:sqlSessionFactory build():

第一:使用dom4j解析配置文件,将解析出来的内容封装到Configuration和MappedStatement中

第二:创建SqlSessionFactory的实现类DefaultSqlSession

3、创建SqlSessionFactory:

方法:openSession() : 获取sqlSession接口的实现类实例对象

4、创建sqlSession接口及实现类:主要封装crud方法

方法:selectList(String statementId,Object param):查询所有

selectOne(String statementId,Object param):查询单个

具体实现:封装JDBC完成对数据库表的查询操作

涉及到的设计模式:

Builder构建者设计模式、工厂模式、代理模式

4、 自定义框架实现

在使用端项目中创建配置配置文件

创建 sqlMapConfig.xml

<configuration>
    <!--数据库连接信息-->
    <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
    <property name="jdbcUrl" value="jdbc:mysql:///zdy_mybatis"></property>
    <property name="user" value="root"></property>
    <property name="password" value="root"></property>
    <! --引入sql配置信息-->
    <mapper resource="mapper.xml"></mapper>
</configuration>

mapper.xml

<mapper namespace="User">
    <select id="selectOne" paramterType="com.tao.pojo.User" resultType="com.tao.pojo.User">
    	select * from user where id = #{id} and username =#{username}
    </select>
    <select id="selectList" resultType="com.tao.pojo.User">
    	select * from user
    </select>
</mapper>

User实体

public class User {
    //主键标识
    private Integer id;
    //用户名
    private String username;
    
    public Integer getId() {
    return id;
    }
    
    public void setId(Integer id) {
    this.id = id;
    }
    
    public String getUsername() {
    return username;
    }
    
    public void setUsername(String username) {
    this.username = username;
    }
    
    @Override
    public String toString() {
    return "User{" +
    "id=" + id +
    ", username='" + username + '\\'' + '}';
    }
}

再创建一个Maven子工程并且导入需要用到的依赖坐标

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.encoding>UTF-8</maven.compiler.encoding>
    <java.version>1.8</java.version>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
</properties>

<dependencies>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.17</version>
    </dependency>
    
    <dependency>
        <groupId>c3p0</groupId>
        <artifactId>c3p0</artifactId>
        <version>0.9.1.2</version>
    </dependency>
    
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.12</version>
    </dependency>
    
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.10</version>
    </dependency>
    
    <dependency>
        <groupId>dom4j</groupId>
        <artifactId>dom4j</artifactId>
        <version>1.6.1</version>
    </dependency>
    
    <dependency>
        <groupId>jaxen</groupId>
        <artifactId>jaxen</artifactId>
        <version>1.1.6</version>
    </dependency>
</dependencies>

Configuration

public class Configuration {
    //数据源
    private DataSource dataSource;
    //map集合: key:statementId 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;
    }
}

MappedStatement

public class MappedStatement {
    //id
    private Integer id;
    //sql语句
    private String sql;
    //输入参数
    private Class<?> paramterType;
    //输出参数
    private Class<?> resultType;
    public Integer getId() {
    	return id;
    }
    public void setId(Integer id) {
    	this.id = id;
    }
    public String getSql() {
    	return sql;
    }
    public void setSql(String sql) {
    	this.sql = sql;
    }
    public Class<?> getParamterType() {
    	return paramterType;
    }
    public void setParamterType(Class<?> paramterType) {
    	this.paramterType = paramterType;
    }
    public Class<?> getResultType() {
    	return resultType;
    }
    public void setResultType(Class<?> resultType) {
    	this.resultType = resultType;
    }
}

Resources

public class Resources {
	public static InputStream getResourceAsSteam(String path){ 
    	InputStream resourceAsStream = Resources.class.getClassLoader.getResourceAsStream(path);
		return resourceAsStream;
	}
}

SqlSessionFactoryBuilder

public class SqlSessionFactoryBuilder {
	private Configuration configuration;
	public SqlSessionFactoryBuilder() {
		this.configuration = new Configuration();
	}
	public SqlSessionFactory build(InputStream inputStream) throws 
        	DocumentException, PropertyVetoException, ClassNotFoundException {
		//1.解析配置文件,封装Configuration XMLConfigerBuilder
		xmlConfigerBuilder = new XMLConfigerBuilder(configuration);
		Configuration configuration =
					xmlConfigerBuilder.parseConfiguration(inputStream);
		//2.创建 sqlSessionFactory
		SqlSessionFactory sqlSessionFactory = new
					DefaultSqlSessionFactory(configuration);
		return sqlSessionFactory;
	}
}

XMLConfigerBuilder

public class XMLConfigerBuilder {
    private Configuration configuration;
    public XMLConfigerBuilder(Configuration configuration) {
    	this.configuration = new Configuration();
    }
    public Configuration parseConfiguration(InputStream inputStream) throws
        DocumentException, PropertyVetoException, ClassNotFoundException {
        Document document = new SAXReader().read(inputStream); //<configuation>
        Element rootElement = document.getRootElement();
        List<Element> propertyElements = rootElement.selectNodes("//property");
        Properties properties = new Properties();
        for (Element propertyElement : propertyElements) {
            String name = propertyElement.attributeValue("name");
            String value = propertyElement.attributeValue("value");
            properties.setProperty(name,value);
    	}
        //连接池
        ComboPooledDataSource comboPooledDataSource = new
        ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        comboPooledDataSource.setUser(properties.getProperty("username"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));
        //填充 configuration
        configuration.setDataSource(comboPooledDataSource);
        //mapper 部分
        List<Element> mapperElements = rootElement.selectNodes("//mapper");
        XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
        for (Element mapperElement : mapperElements) {
            String mapperPath = mapperElement.attributeValue("resource");
            InputStream resourceAsSteam = Resources.getResourceAsSteam(mapperPath);
            xmlMapperBuilder.parse(resourceAsSteam);
        }
		return configuration;
	}
}

XMLMapperBuilder

public class XMLMapperBuilder {

    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream inputStream) throws DocumentException {

        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();

        String namespace = rootElement.attributeValue("namespace");

        List<Element> list = rootElement.selectNodes("//select");
        for (Element element : list) {
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String paramterType = element.attributeValue("paramterType");
            String sqlText = element.getTextTrim();
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setParamterType(paramterType);
            mappedStatement.setResultType(resultType);
            mappedStatement.setSql(sqlText);
            String key = namespace + "." + id;
            configuration.getMappedStatementMap().put(key,mappedStatement);
        Java精进-手写持久层框架

Java精进-手写持久层框架

Java精进-手写持久层框架

微人事项目-mybatis-持久层

Mybatis学习之自定义持久层框架 为什么要用框架而不直接用JDBC?

《Java手写系列》-手写MyBatis框架