Spring集成MyBaties中sqlSessionFactory的创建[通俗易懂]

Spring集成MyBaties中sqlSessionFactory的创建[通俗易懂]Spring的核心思想就是IOC(InversionOfControl),中文意思就是控制反转,将创建对象的任务交由工厂来处理,同时还可以管理类与类之间的关系,从而提出了依赖注入的概念。先来了解对象的分类:1.简单对象:可以通过new的方式创建的对象,例如UserServiceImle、User类等2.复杂对象:不能通过new的方式创建的对象,例如sqlSessionFact…

大家好,又见面了,我是你们的朋友全栈君。

Spring 的核心思想就是IOC(Inversion Of Control),中文意思就是控制反转,将创建对象的任务交由工厂来处理,同时还可以管理类与类之间的关系,从而提出了依赖注入的概念。

先来了解对象的分类:

 1.简单对象:可以通过new的方式创建的对象,例如UserServiceImle 、User类等

 2.复杂对象:不能通过new的方式创建的对象,例如sqlSessionFactory等

对于简单对象来讲,我们只需要配置相关的spring配置文件即可:

	//配置UserServiceImpl
    <bean id="userService" class="com.baizhi.staticproxy.UserServiceImpl"></bean>
    //依赖注入
    <bean id="userServiceStaticProxy" class="com.baizhi.staticproxy.UserServiceStaticProxy">
        <property name="userService" ref="userService"></property>
    </bean>

那么问题来了,我们如何来创建复杂对象的,这也就是MyBaties解决和spring集成的一个问题:

	如何创建复杂对象sqlSessionFactory?????

spring官方是没有给MyBaties提供相关的服务的,因为spring有自己的数据化持久的工具jdbcTemplate,为了推广自己的工具,所以就造成了今天问题的来源。但是spring的用户量还是很大的,MyBaties必须自己想办法解决问题,于是就自己开发相关jar包,共大家做spring和MyBaties的集成:

其中问题的核心就是	如何创建复杂对象sqlSessionFactory?????

Spring为我们提供了一个解决创建复杂对象的接口,叫做FactoryBean:

package org.springframework.beans.factory;

public interface FactoryBean<T> {
//创建sqlSessionFactory
    T getObject() throws Exception;
//获取返回值类型
    Class<?> getObjectType();
//单例还是多例
    boolean isSingleton();
}

我们只需要实现这个接口,并覆盖这三个方法即可,当然你,这个类不需要我们自己写,mybaties已经帮我们写了:

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package org.mybatis.spring;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.ibatis.builder.xml.XMLConfigBuilder;
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.cache.Cache;
import org.apache.ibatis.executor.ErrorContext;
import org.apache.ibatis.io.VFS;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;
import org.apache.ibatis.mapping.DatabaseIdProvider;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.reflection.factory.ObjectFactory;
import org.apache.ibatis.reflection.wrapper.ObjectWrapperFactory;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.type.TypeHandler;
import org.mybatis.spring.transaction.SpringManagedTransactionFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.NestedIOException;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

public class SqlSessionFactoryBean implements FactoryBean<SqlSessionFactory>, InitializingBean, ApplicationListener<ApplicationEvent> {
    private static final Log LOGGER = LogFactory.getLog(SqlSessionFactoryBean.class);
    private Resource configLocation;
    private Configuration configuration;
    //注册mapper文件
    private Resource[] mapperLocations;
    //引入数据源
    private DataSource dataSource;
    private TransactionFactory transactionFactory;
    private Properties configurationProperties;
    private SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
    //创建sqlsqlSessionFactory
    private SqlSessionFactory sqlSessionFactory;
    private String environment = SqlSessionFactoryBean.class.getSimpleName();
    private boolean failFast;
    private Interceptor[] plugins;
    private TypeHandler<?>[] typeHandlers;
    private String typeHandlersPackage;
    private Class<?>[] typeAliases;
    //起别名
    private String typeAliasesPackage;
    private Class<?> typeAliasesSuperType;
    private DatabaseIdProvider databaseIdProvider;
    private Class<? extends VFS> vfs;
    private Cache cache;
    private ObjectFactory objectFactory;
    private ObjectWrapperFactory objectWrapperFactory;
	//提供无参的构造方法
    public SqlSessionFactoryBean() {
    }
	//提供所有成员变量的set方法,用来做set注入
    public void setObjectFactory(ObjectFactory objectFactory) {
        this.objectFactory = objectFactory;
    }

    public void setObjectWrapperFactory(ObjectWrapperFactory objectWrapperFactory) {
        this.objectWrapperFactory = objectWrapperFactory;
    }

    public DatabaseIdProvider getDatabaseIdProvider() {
        return this.databaseIdProvider;
    }

    public void setDatabaseIdProvider(DatabaseIdProvider databaseIdProvider) {
        this.databaseIdProvider = databaseIdProvider;
    }

    public Class<? extends VFS> getVfs() {
        return this.vfs;
    }

    public void setVfs(Class<? extends VFS> vfs) {
        this.vfs = vfs;
    }

    public Cache getCache() {
        return this.cache;
    }

    public void setCache(Cache cache) {
        this.cache = cache;
    }

    public void setPlugins(Interceptor[] plugins) {
        this.plugins = plugins;
    }

    public void setTypeAliasesPackage(String typeAliasesPackage) {
        this.typeAliasesPackage = typeAliasesPackage;
    }

    public void setTypeAliasesSuperType(Class<?> typeAliasesSuperType) {
        this.typeAliasesSuperType = typeAliasesSuperType;
    }

    public void setTypeHandlersPackage(String typeHandlersPackage) {
        this.typeHandlersPackage = typeHandlersPackage;
    }

    public void setTypeHandlers(TypeHandler<?>[] typeHandlers) {
        this.typeHandlers = typeHandlers;
    }

    public void setTypeAliases(Class<?>[] typeAliases) {
        this.typeAliases = typeAliases;
    }

    public void setFailFast(boolean failFast) {
        this.failFast = failFast;
    }

    public void setConfigLocation(Resource configLocation) {
        this.configLocation = configLocation;
    }

    public void setConfiguration(Configuration configuration) {
        this.configuration = configuration;
    }

    public void setMapperLocations(Resource[] mapperLocations) {
        this.mapperLocations = mapperLocations;
    }

    public void setConfigurationProperties(Properties sqlSessionFactoryProperties) {
        this.configurationProperties = sqlSessionFactoryProperties;
    }

    public void setDataSource(DataSource dataSource) {
        if (dataSource instanceof TransactionAwareDataSourceProxy) {
            this.dataSource = ((TransactionAwareDataSourceProxy)dataSource).getTargetDataSource();
        } else {
            this.dataSource = dataSource;
        }

    }

    public void setSqlSessionFactoryBuilder(SqlSessionFactoryBuilder sqlSessionFactoryBuilder) {
        this.sqlSessionFactoryBuilder = sqlSessionFactoryBuilder;
    }

    public void setTransactionFactory(TransactionFactory transactionFactory) {
        this.transactionFactory = transactionFactory;
    }

    public void setEnvironment(String environment) {
        this.environment = environment;
    }

    public void afterPropertiesSet() throws Exception {
        Assert.notNull(this.dataSource, "Property 'dataSource' is required");
        Assert.notNull(this.sqlSessionFactoryBuilder, "Property 'sqlSessionFactoryBuilder' is required");
        Assert.state(this.configuration == null && this.configLocation == null || this.configuration == null || this.configLocation == null, "Property 'configuration' and 'configLocation' can not specified with together");
        this.sqlSessionFactory = this.buildSqlSessionFactory();
    }
//核心方法一
    protected SqlSessionFactory buildSqlSessionFactory() throws IOException {
        XMLConfigBuilder xmlConfigBuilder = null;
        Configuration configuration;
        if (this.configuration != null) {
            configuration = this.configuration;
            if (configuration.getVariables() == null) {
                configuration.setVariables(this.configurationProperties);
            } else if (this.configurationProperties != null) {
                configuration.getVariables().putAll(this.configurationProperties);
            }
        } else if (this.configLocation != null) {
            xmlConfigBuilder = new XMLConfigBuilder(this.configLocation.getInputStream(), (String)null, this.configurationProperties);
            configuration = xmlConfigBuilder.getConfiguration();
        } else {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Property 'configuration' or 'configLocation' not specified, using default MyBatis Configuration");
            }

            configuration = new Configuration();
            if (this.configurationProperties != null) {
                configuration.setVariables(this.configurationProperties);
            }
        }

        if (this.objectFactory != null) {
            configuration.setObjectFactory(this.objectFactory);
        }

        if (this.objectWrapperFactory != null) {
            configuration.setObjectWrapperFactory(this.objectWrapperFactory);
        }

        if (this.vfs != null) {
            configuration.setVfsImpl(this.vfs);
        }

        String[] typeHandlersPackageArray;
        String[] var4;
        int var5;
        int var6;
        String packageToScan;
        if (StringUtils.hasLength(this.typeAliasesPackage)) {
            typeHandlersPackageArray = StringUtils.tokenizeToStringArray(this.typeAliasesPackage, ",; \t\n");
            var4 = typeHandlersPackageArray;
            var5 = typeHandlersPackageArray.length;

            for(var6 = 0; var6 < var5; ++var6) {
                packageToScan = var4[var6];
                configuration.getTypeAliasRegistry().registerAliases(packageToScan, this.typeAliasesSuperType == null ? Object.class : this.typeAliasesSuperType);
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Scanned package: '" + packageToScan + "' for aliases");
                }
            }
        }

        int var27;
        if (!ObjectUtils.isEmpty(this.typeAliases)) {
            Class[] var25 = this.typeAliases;
            var27 = var25.length;

            for(var5 = 0; var5 < var27; ++var5) {
                Class<?> typeAlias = var25[var5];
                configuration.getTypeAliasRegistry().registerAlias(typeAlias);
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Registered type alias: '" + typeAlias + "'");
                }
            }
        }

        if (!ObjectUtils.isEmpty(this.plugins)) {
            Interceptor[] var26 = this.plugins;
            var27 = var26.length;

            for(var5 = 0; var5 < var27; ++var5) {
                Interceptor plugin = var26[var5];
                configuration.addInterceptor(plugin);
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Registered plugin: '" + plugin + "'");
                }
            }
        }

        if (StringUtils.hasLength(this.typeHandlersPackage)) {
            typeHandlersPackageArray = StringUtils.tokenizeToStringArray(this.typeHandlersPackage, ",; \t\n");
            var4 = typeHandlersPackageArray;
            var5 = typeHandlersPackageArray.length;

            for(var6 = 0; var6 < var5; ++var6) {
                packageToScan = var4[var6];
                configuration.getTypeHandlerRegistry().register(packageToScan);
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Scanned package: '" + packageToScan + "' for type handlers");
                }
            }
        }

        if (!ObjectUtils.isEmpty(this.typeHandlers)) {
            TypeHandler[] var28 = this.typeHandlers;
            var27 = var28.length;

            for(var5 = 0; var5 < var27; ++var5) {
                TypeHandler<?> typeHandler = var28[var5];
                configuration.getTypeHandlerRegistry().register(typeHandler);
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Registered type handler: '" + typeHandler + "'");
                }
            }
        }

        if (this.databaseIdProvider != null) {
            try {
                configuration.setDatabaseId(this.databaseIdProvider.getDatabaseId(this.dataSource));
            } catch (SQLException var24) {
                throw new NestedIOException("Failed getting a databaseId", var24);
            }
        }

        if (this.cache != null) {
            configuration.addCache(this.cache);
        }

        if (xmlConfigBuilder != null) {
            try {
                xmlConfigBuilder.parse();
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Parsed configuration file: '" + this.configLocation + "'");
                }
            } catch (Exception var22) {
                throw new NestedIOException("Failed to parse config resource: " + this.configLocation, var22);
            } finally {
                ErrorContext.instance().reset();
            }
        }

        if (this.transactionFactory == null) {
            this.transactionFactory = new SpringManagedTransactionFactory();
        }

        configuration.setEnvironment(new Environment(this.environment, this.transactionFactory, this.dataSource));
        if (!ObjectUtils.isEmpty(this.mapperLocations)) {
            Resource[] var29 = this.mapperLocations;
            var27 = var29.length;

            for(var5 = 0; var5 < var27; ++var5) {
                Resource mapperLocation = var29[var5];
                if (mapperLocation != null) {
                    try {
                        XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(mapperLocation.getInputStream(), configuration, mapperLocation.toString(), configuration.getSqlFragments());
                        xmlMapperBuilder.parse();
                    } catch (Exception var20) {
                        throw new NestedIOException("Failed to parse mapping resource: '" + mapperLocation + "'", var20);
                    } finally {
                        ErrorContext.instance().reset();
                    }

                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("Parsed mapper file: '" + mapperLocation + "'");
                    }
                }
            }
        } else if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Property 'mapperLocations' was not specified or no matching resources found");
        }

        return this.sqlSessionFactoryBuilder.build(configuration);
    }

    public SqlSessionFactory getObject() throws Exception {
        if (this.sqlSessionFactory == null) {
            this.afterPropertiesSet();
        }

        return this.sqlSessionFactory;
    }
	//核心方法二
    public Class<? extends SqlSessionFactory> getObjectType() {
        return this.sqlSessionFactory == null ? SqlSessionFactory.class : this.sqlSessionFactory.getClass();
    }
	//核心方法三
    public boolean isSingleton() {
        return true;
    }

    public void onApplicationEvent(ApplicationEvent event) {
        if (this.failFast && event instanceof ContextRefreshedEvent) {
            this.sqlSessionFactory.getConfiguration().getMappedStatementNames();
        }

    }
}

上面的实现类实现比较复杂,喜欢啃源码的同学可以细细品味一下,对于实战开发来讲,我们只需要知道,我们的工作就是直接用,并且进行如下的先关配置即可:

<!--自动创建sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--构建sqlSession需要数据源-->
        <property name="dataSource" ref="basicDataSource"></property>

        <!--起别名   给该包下所有的类起别名,默认别名为该类的类名-->
        <property name="typeAliasesPackage" ><value>com.baizhi.entity</value></property>

        <!--mapper文件注册-->
        <property name="mapperLocations">
            <list><!--默认为com.baizhi.mapper包下面以Mapper.xml结尾的文件进行注册-->
                <value>com/baizhi/mapper/*Mapper.xml</value>
            </list>
        </property>
    </bean>

在这个配置中,主要完成的任务只有两件:

1.拿到数据源

2.mapper文件的注册

还有就是关于创建dao实现类,MyBatirs也进行了相关的优化封装,我们可以在spring配置文件中直接去配置:

<!--自动创建Dao的实现类对象-->
    <bean id="mapperScannerConfiger" class="org.mybatis.spring.mapper.MapperScannerConfigurer">

      <!--告知Spring  为com.baizhi.dao包下面的所有接口构建DAO的实现类对象-->
        <property name="basePackage">
            <value>com.baizhi.dao</value>
        </property>

    </bean>
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/145092.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

  • linux添加防火墙_centos防火墙设置与端口开放的方法

    linux添加防火墙_centos防火墙设置与端口开放的方法一、介绍当设置ip过滤的时候,如果ip较多,经常修改,修改防火墙规则比较麻烦,可以使用ipset,ipset是一个集合,防火墙可以添加集合,只需要一条防火墙规则就可以实现整个集合里面ip的过滤iptables-IINPUT-mset–match-setbanipsrc-ptcp–destination-port80-jDROPTYPENAME:=method:datatype[,datatype[,datatype]]可以使用的method:bitmap,ha

  • 四旋翼飞行器图片(4轴飞行器飞行运动中有)

    1、未知区域地形的构建2、农业方面的应用:(1)运用图像识别技术检测果实数量;(2)检测作物是否发生病虫害,因为当作物出现病虫害时都会有相应的表现现状。具体见链接http://www.aiweibang.com/yuedu/153474153.html3、高层建筑物的搭建

  • 使用LayUI操作数据表格「建议收藏」

    使用LayUI操作数据表格「建议收藏」接着 上一篇 继续完善我们的demo,这次我们加一个搜索按钮搜索源代码地址点我在table标签的上方,加入这样一组html<divclass="demo

  • 10条PHP编程习惯助你找工作

    10条PHP编程习惯助你找工作

    2021年10月15日
  • 图卷积网络 GCN Graph Convolutional Network(谱域GCN)的理解和详细推导[通俗易懂]

    图卷积网络 GCN Graph Convolutional Network(谱域GCN)的理解和详细推导[通俗易懂]文章目录1.为什么会出现图卷积神经网络?2.图卷积网络的两种类型2.1vertexdomain(spatialdomain):顶点域(空间域)2.2spectraldomain:频域方法(谱方法)3.什么是拉普拉斯矩阵?3.1常用的几种拉普拉斯矩阵普通形式的拉普拉斯矩阵对称归一化的拉普拉斯矩阵(SymmetricnormalizedLaplacian)随机游走归一化拉普拉斯矩…

  • GBDT算法总结

    GBDT算法总结前向分布算法负梯度拟合在上一节中,我们介绍了GBDT的基本思路,但是没有解决损失函数拟合方法的问题。针对这个问题,大牛Freidman提出了用损失函数的负梯度来拟合本轮损失的近似值,进而拟合一个CART回归树。第t轮的第i个样本的损失函数的负梯度表示为    利用(xi,rti)(i=1…

    2022年10月12日

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号