码迷,mamicode.com
首页 > 其他好文 > 详细

Mybatis--第?部分:?定义持久层框架

时间:2021-02-01 12:43:34      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:enc   dal   url   jdb   declare   数据   执行sql   except   desc   

?定义持久层框架

 分析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();

分析JDBC操作问题                  解决方案

  1.数据库配置信息存在硬编码问题              1.配置文件

  2.频繁创建释放数据库连接                 2.连接池解决

技术图片

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

自定义持久层框架设计思路

技术图片

 

自定义持久层框架实现步骤

1. 环境基本部署搭建   

技术图片

 技术图片

 第一步 :引入持久层框架依赖

1.zdyMybatis_test使用端:
<?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.mytest</groupId>
    <artifactId>zdyMybatis_test</artifactId>
    <version>1.0-SNAPSHOT</version>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.encoding>UTF-8</maven.compiler.encoding>
        <java.version>1.8</java.version>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.mytest</groupId>
            <artifactId>zdyMybatis</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
    </dependencies>

</project>

2.zdyMybatis 框架端:

<?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.homework</groupId>
    <artifactId>mybatis</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>

 第二步 :添加配置文件

  使?端:
    提供核?配置?件:
    sqlMapConfig.xml : 存放数据源信息,引?mapper.xml
    Mapper.xml : sql语句的配置?件信息
 
 sqlMapConfig.xml :
<configuration>
    <!-- 当前使用5.7数据库进行配置 -->
    <!--数据库配置信息-->
   <dateSourse>
       <property name="driverClass" value="com.mysql.cj.jdbc.Driver"></property>
       <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/mybatis_test"></property>
       <property name="username" value="root"></property>
       <property name="password" value="root"></property>
   </dateSourse>

    <!--存放mapper.xml的全路径-->
    <mapper resource="UserMapper.xml"></mapper>

</configuration>

  Mapper.xml :

<mapper namespace="com.mybatis.dao.IUserDao">

    <!--sql的唯一标识:namespace.id来组成 : statementId-->
    <select id="findAll" resultType="com.mybatis.pojo.User" >
        select * from user
    </select>

    <!--
        User user = new User()
        user.setId(1);
        user.setUsername("zhangsan")
    -->
    <select id="findByCondition" resultType="com.mybatis.pojo.User" paramterType="com.mybatis.pojo.User">
        select * from user where id = #{id} and username = #{username}
    </select>


</mapper>

具体实现

  1)加载配置文件,根据配置文件路径,加载成字节输入流,存储在内存
    创建 Resource类,方法 : public static InputStream getResourceAsSteam(String path)    
package com.mybatis.io;

import java.io.InputStream;

/**
 * @Author: denghy
 * @DateTime: 2021/1/28 11:28
 * @Description: TODO
 * @package: com.mybatis.io
 */
public class Resources {
    // 根据配置文件的路径,将配置文件加载成字节输入流,存储在内存中
    public static InputStream getResourceAsSteam(String path){
        InputStream resourceAsStream = Resources.class.getClassLoader().getResourceAsStream(path);
        return  resourceAsStream;

    }
}

 2)创建两个javaBean(容器对象)存放对配置文件解析的内容

  MappedStatement : 映射配置类,存放解析的userMapper.xml内容

  Configruation : 核心配置类,存放解析的sqlMapperConfig.xml内容

package com.mybatis.pojo;

/**
 * @Author: denghy
 * @DateTime: 2021/1/28 13:27
 * @Description: TODO
 * @package: com.mybatis.pojo
 */
public class MappedStatement {
    private String id;
    private String resultType;
    private String paramterType;
    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.mybatis.pojo;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

public class Configuration {

    private DataSource dataSource;

    /*
    *   key: statementid  value:封装好的mappedStatement对象
     * */
    Map<String,MappedStatement> mappedStatementMap = new HashMap<>();

    public DataSource getDataSource() {
        return dataSource;
    }

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public Map<String, MappedStatement> getMappedStatementMap() {
        return mappedStatementMap;
    }

    public void setMappedStatementMap(Map<String, MappedStatement> mappedStatementMap) {
        this.mappedStatementMap = mappedStatementMap;
    }
}

  3)用dome4j进行解析配置文件:

    创建一个SqlSessionFactoryBuilder类,public SqlSessionFactory build(InputStream in)  方法

    1. 使用deom4j 解析,将解析的内容存放在容器中 

    2 .SqlSessionFactory 创建 sqlSession对象,用到  工厂模式

   1)使用dome4j 解析配置文件,并存放在configruation
    XMLConfigBuilder xmlConfigBuilder = new XMLConfigBuilder();
    Configuration configuration = xmlConfigBuilder.parseConfig(inputStream);
package com.mybatis.sqlSession;

import com.mybatis.config.XMLConfigBuilder;
import com.mybatis.pojo.Configuration;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;

/**
 * @Author: denghy
 * @DateTime: 2021/1/28 14:41
 * @Description: TODO
 * @package: com.mybatis.sqlSession
 */
public class SqlSessionFactoryBuilder {

    public SqlSessionFactory build(InputStream inputStream) throws DocumentException, PropertyVetoException {
        //使用dome4j 解析配置文件,并存放在configruation
        XMLConfigBuilder xmlConfigBuilder = new XMLConfigBuilder();
        Configuration configuration = xmlConfigBuilder.parseConfig(inputStream);

        //创建SqlsessionFatory对象,产生SqlSession
        DefaultSqlSessionFactory defaultSqlSessionFactory = new DefaultSqlSessionFactory(configuration);

        return null;
    }

}
package com.mybatis.config;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.mybatis.io.Resources;
import com.mybatis.pojo.Configuration;
import com.sun.javafx.scene.control.skin.ComboBoxPopupControl;
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;

/**
 * @Author: denghy
 * @DateTime: 2021/1/28 14:44
 * @Description: 该方法就是使用dom4j对配置文件进行解析,封装Configuration
 * @package: com.mybatis.config
 */
public class XMLConfigBuilder {

    private Configuration configuration;

    public XMLConfigBuilder() {
        this.configuration =  new Configuration();
    }

    public Configuration parseConfig(InputStream inputStream) throws DocumentException, PropertyVetoException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        List<Element> list = rootElement.selectNodes("//property");
        Properties properties = new Properties();
        for (Element element : list) {
            String name = element.attributeValue("name");
            String value = element.attributeValue("value");
            properties.setProperty(name,value);
        }

        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("dirverClass"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        comboPooledDataSource.setUser(properties.getProperty("username"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));
        configuration.setDataSource(comboPooledDataSource);//放入数据源

        //mapper.xml解析: 拿到路径--字节输入流---dom4j进行解析
        List<Element> mapperList = rootElement.selectNodes("//mapper");
        for (Element element : mapperList) {
            String mapperPath = element.attributeValue("resource");

            InputStream resourceAsSteam = Resources.getResourceAsSteam(mapperPath);
            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);

            xmlMapperBuilder.parse(resourceAsSteam);

        }
        return configuration;
    }

}
package com.mybatis.config;

import com.mybatis.pojo.Configuration;
import com.mybatis.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 * @Author: denghy
 * @DateTime: 2021/1/28 15:05
 * @Description: TODO
 * @package: com.mybatis.config
 */
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();
        List<Element> list = rootElement.selectNodes("//select");
        //获取sql的唯一标识:namespace.id来组成 : statementId
        String namespace = rootElement.attributeValue("namespace");


        for (Element element : list) {
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String paramterType = element.attributeValue("paramterType");
            String sql = element.getTextTrim();

            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setResultType(resultType);
            mappedStatement.setParamterType(paramterType);
            mappedStatement.setSql(sql);

            configuration.getMappedStatementMap().put(namespace+"."+id,mappedStatement);
        }

    }
}

  4)创建接口:SplsessionFactory

           实现类:DefaultSqlSessionFactory

    openSession 方法   创建 SqlSession

技术图片

public interface SqlSessionFactory {

    public SqlSession openSession();
}
public class DefaultSqlSessionFactory implements SqlSessionFactory{

    private Configuration configuration;

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

    @Override
    public SqlSession openSession() {
        return new DefaultSqlSession(configuration);
    }
}

  5)创建接口:SqlSession

      实现类:DefaultSqlSession

public class DefaultSqlSession implements SqlSession {
    private Configuration configuration;

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

    @Override
    public <E> List<E> selectList(String statementid, Object... params) throws Exception {
        //将要去完成对simpleExecutor里的query方法的调用
        simpleExecutor simpleExecutor = new simpleExecutor();
        List<Object> list = simpleExecutor.query(configuration, configuration.getMappedStatementMap().get(statementid), params);
        return (List<E>) list;
    }

    @Override
    public <T> T selectOne(String statementid, Object... params) throws Exception {
        List<Object> list = selectList(statementid, params);
        if(list.size()==1){
            Object o = list.get(0);
            return (T) o;
        }else {
            throw new RuntimeException("查询结果过多活返回结果过多");
        }
    }

    @Override
    public <T> T getMapper(Class<?> mapperClass) {
// 使用JDK动态代理来为Dao接口生成代理对象,并返回

Object proxyInstance = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // 底层都还是去执行JDBC代码 //根据不同情况,来调用selctList或者selectOne
        // 准备参数 1:statmentid :sql语句的唯一标识:namespace.id= 接口全限定名.方法名
        // 方法名:findAll
        String methodName = method.getName();
        String className = method.getDeclaringClass().getName();

        String statementId = className+"."+methodName;

        // 准备参数2:params:args
        // 获取被调用方法的返回值类型
        Type genericReturnType = method.getGenericReturnType();
        // 判断是否进行了 泛型类型参数化
        if(genericReturnType instanceof ParameterizedType){
            List<Object> objects = selectList(statementId, args);
            return objects;
        }

        return selectOne(statementId,args);

    }
});

return (T) proxyInstance;
 } }

 6. 编写接口:Executor query + 实现类  simpleExecutor

public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
        //注册驱动
        Connection connection = configuration.getDataSource().getConnection();

        //获取sql
        String sql = mappedStatement.getSql();
        BoundSql boundSql = getBoundSql(sql);

        //获取预处理对象
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());

        //获取参数
        String paramterType = mappedStatement.getParamterType();
        Class<?> paramterTypeClass = getClassType(paramterType);

        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappings();
        for (int i = 0; i < parameterMappingList.size(); i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            String content = parameterMapping.getContent();

            Field declaredField = paramterTypeClass.getDeclaredField(content);
            declaredField.setAccessible(true);
            Object o = declaredField.get(params[0]);
            preparedStatement.setObject(i+1,o);
        }
        //执行sql
        ResultSet resultSet = preparedStatement.executeQuery();
        String resultType = mappedStatement.getResultType();
        Class<?> resultTypeClass = getClassType(resultType);
        ArrayList<Object> objects = new ArrayList<>();
        //封装返回结果集
        while (resultSet.next()){
            Object o =resultTypeClass.newInstance();
            //元数据
            ResultSetMetaData metaData = resultSet.getMetaData();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                // 字段名
                String columnName = metaData.getColumnName(i);
                // 字段的值
                Object value = resultSet.getObject(columnName);

                //使用反射或者内省,根据数据库表和实体的对应关系,完成封装
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultTypeClass);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(o,value);
            }
            objects.add(o);
        }

        return (List<E>) objects;
    }

 

 

 

 

 

 

 

Mybatis--第?部分:?定义持久层框架

标签:enc   dal   url   jdb   declare   数据   执行sql   except   desc   

原文地址:https://www.cnblogs.com/denghy-301/p/14352144.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!