sqlsessionfactory和sqlsession

Springboot 自定义mybatis 拦截器,实现我们要的扩展 前言 相信大家对拦截器并不陌生,对mybatis也不陌生。 有用过pagehelper的,那么对mybatis拦截器也不陌生了,按照使用的规则触发sql拦截,帮我们自动添加分页参数 。 那么今天,我们的实践 自定义mybatis拦截器也是如此, 本篇文章实践的效果:针对一些使用 单个实体类去接收返回结果的 mapper方法,我们拦截检测,如果没写 LIMIT 1 ,我们将自动帮忙填充,达到查找单条数据 效率优化的效果。 ps: 当然,跟着该篇学会了这个之后,那么可以扩展的东西就多了,大家按照 阅读详情

目录

前言:

一、 SqlSessionFactory

二、SqlSession

三、SqlSessionFactory和SqlSession实现过程


前言:

学习框架一个比较好的路径阅读源码,本文介绍的SqlSessionFactory和SqlSession,可以通过了解SqlSessionFactory接口和SqlSession接口以及两个的实现类入手,去看源码了解实现过程.最好能把项目下载到本地,慢慢分析实现过程。

Myabtis官网:http://www.mybatis.org/
github地址:https://github.com/mybatis/mybatis-3

MyBatis的持久化解决方案是将用户从原始的JDBC访问中解放出来,用户只需要定义需要操作的SQL语句,无须关注底层的JDBC操作,就可以以面向对象的方式来进行持久化层操作。底层数据库连接的获取,数据访问的实现,事务控制等都无须用户关心,从而将应用层从底层的JDBC/JTA API抽取出来。通过配置文件管理JDBC连接,让MyBatis解决持久化的实现。在MyBatis中的常见对象有SqlSessionFactory和SqlSession。

本文这种介绍一下两者的概念和使用。

一、 SqlSessionFactory

SqlSessionFactory是MyBatis的关键对象,它是个单个数据库映射关系经过编译后的内存镜像,SqlSessionFactory对象的实例可以通过SqlSessionFactoryBuilder对象类获得,而SqlSessionFactoryBuilder则可以从XML配置文件或一个预先定制的Configuration的实例构建出SqlSessionFactory的实例。每一个MyBatis的应用程序都以一个SqlSessionFactory对象的实例为核心。同时SqlSessionFactory也是线程安全的,SqlSessionFactory一旦被创建,应该在应用执行期间都存在。在应用运行期间不要重复创建多次,建议使用单例模式.SqlSessionFactory是创建SqlSession的工厂。

//SqlSessionFactory接口源码如下所示:

package org.apache.ibatis.session;

import java.sql.Connection;

public interface SqlSessionFactory {

  SqlSession openSession();//这个方法最经常用,用来创建SqlSession对象.

  SqlSession openSession(boolean autoCommit);
  SqlSession openSession(Connection connection);
  SqlSession openSession(TransactionIsolationLevel level);

  SqlSession openSession(ExecutorType execType);
  SqlSession openSession(ExecutorType execType, boolean autoCommit);
  SqlSession openSession(ExecutorType execType, TransactionIsolationLevel level);
  SqlSession openSession(ExecutorType execType, Connection connection);

  Configuration getConfiguration();

}

二、SqlSession

SqlSession是MyBatis的关键对象,是执行持久化操作的独享,类似于JDBC中的Connection。它是应用程序与持久层之间执行交互操作的一个单线程对象,也是MyBatis执行持久化操作的关键对象。SqlSession对象完全包含以数据库为背景的所有执行SQL操作的方法,它的底层封装了JDBC连接,可以用SqlSession实例来直接执行被映射的SQL语句。每个线程都应该有它自己的SqlSession实例。SqlSession的实例不能被共享,同时SqlSession也是线程不安全的,绝对不能讲SqlSeesion实例的引用放在一个类的静态字段甚至是实例字段中。也绝不能将SqlSession实例的引用放在任何类型的管理范围中,比如Servlet当中的HttpSession对象中。使用完SqlSeesion之后关闭Session很重要,应该确保使用finally块来关闭它。

//SqlSession接口源码如下所示:

package org.apache.ibatis.session;

import java.io.Closeable;
import java.sql.Connection;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.executor.BatchResult;

public interface SqlSession extends Closeable {

  <T> T selectOne(String statement);

  <T> T selectOne(String statement, Object parameter);

  <E> List<E> selectList(String statement);

  <E> List<E> selectList(String statement, Object parameter);

  <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds);

  <K, V> Map<K, V> selectMap(String statement, String mapKey);

  <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey);

  <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey, RowBounds rowBounds);

  void select(String statement, Object parameter, ResultHandler handler);

  void select(String statement, ResultHandler handler);

  void select(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler);

  int insert(String statement);

  int insert(String statement, Object parameter);

  int update(String statement);

  int update(String statement, Object parameter);

  int delete(String statement);

  int delete(String statement, Object parameter);

  void commit();

  void commit(boolean force);

  void rollback();

  void rollback(boolean force);

  List<BatchResult> flushStatements();

  void close();

  void clearCache();

  Configuration getConfiguration();

  <T> T getMapper(Class<T> type);

  Connection getConnection();
}

三、SqlSessionFactory和SqlSession实现过程

mybatis框架主要是围绕着SqlSessionFactory进行的,创建过程大概如下:

(1)、定义一个Configuration对象,其中包含数据源、事务、mapper文件资源以及影响数据库行为属性设置settings

(2)、通过配置对象,则可以创建一个SqlSessionFactoryBuilder对象

(3)、通过 SqlSessionFactoryBuilder 获得SqlSessionFactory 的实例。

(4)、SqlSessionFactory 的实例可以获得操作数据的SqlSession实例,通过这个实例对数据库进行操作

并且如果想按照上述方式得到SqlSessionFactory,最好使用下面的mybatis-config.xml类似的配置。在这里mybatis-config.xml配置文件是没有和Spring配置文件整合过得,如果项目中mybaits的配置文件和Spring配置文件整合过了,则下面的代码运行估计会出错,因为一般spring和mybatis整合过之后,mybatis的配置文件基本没有存在的必要了,之前在mybatis中配置的数据源和事务这两个方面,一般的做法都会spring的配置文件,则下面的代码加载mybatis-config.xml的时候,得不到必要的信息,创建的过程中会有问题。所以在这里先给一份mybatis-config.xml单独的配置文件。

<?xml version="1.0" encoding="UTF-8"?>  
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"  
"http://mybatis.org/dtd/mybatis-3-config.dtd">  

<configuration>   
    <!-- 加载类路径下的属性文件 -->  
    <properties resource="db.properties"/>  

    <!-- 设置类型别名 -->  
    <typeAliases>  
        <typeAlias type="cn.itcast.javaee.mybatis.app04.Student" alias="student"/>  
    </typeAliases>  

    <!-- 设置一个默认的连接环境信息 -->  
    <environments default="mysql_developer">  

        <!-- 连接环境信息,取一个任意唯一的名字 -->  
        <environment id="mysql_developer">  
            <!-- mybatis使用jdbc事务管理方式 -->  
            <transactionManager type="jdbc"/>  
            <!-- mybatis使用连接池方式来获取连接 -->  
            <dataSource type="pooled">  
                <!-- 配置与数据库交互的4个必要属性 -->  
                <property name="driver" value="${mysql.driver}"/>  
                <property name="url" value="${mysql.url}"/>  
                <property name="username" value="${mysql.username}"/>  
                <property name="password" value="${mysql.password}"/>  
            </dataSource>  
        </environment>  

        <!-- 连接环境信息,取一个任意唯一的名字 -->  
        <environment id="oracle_developer">  
            <!-- mybatis使用jdbc事务管理方式 -->  
            <transactionManager type="jdbc"/>  
            <!-- mybatis使用连接池方式来获取连接 -->  
            <dataSource type="pooled">  
                <!-- 配置与数据库交互的4个必要属性 -->  
                <property name="driver" value="${oracle.driver}"/>  
                <property name="url" value="${oracle.url}"/>  
                <property name="username" value="${oracle.username}"/>  
                <property name="password" value="${oracle.password}"/>  
            </dataSource>  
        </environment>  
    </environments>  

    <!-- 加载映射文件-->  
    <mappers>  
        <mapper resource="cn/itcast/javaee/mybatis/app14/StudentMapper.xml"/>  
    </mappers>  

</configuration>  

下面的这行代码功能是通过配置文件mybatis-config.xml,创建SqlSessionFactory对象,然后产生SqlSession,执行SQL语句.而mybatis的初始化发生在:

SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);

如果是spring和mybaits整合之后的配置文件,一般以这种方式实现,SqlSessionFactory的创建:

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <!-- 自动扫描mapping.xml文件 -->
        <property name="mapperLocations" value="classpath:com/cn/mapper/*.xml"></property>
</bean>

关于SqlSessionFactory和SqlSession两个对象给一个具体的使用过程:

package com.cn.testIUserService;

import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.cn.entity.User;

public class MyBatisTest {

    public static void main(String[] args) {
        try {
            //读取mybatis-config.xml文件
            InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
            //初始化mybatis,创建SqlSessionFactory类的实例
            SqlSessionFactory sqlSessionFactory =  new SqlSessionFactoryBuilder().build(resourceAsStream);
            //创建session实例
            SqlSession session = sqlSessionFactory.openSession();
            /*
             * 接下来在这里做很多事情,到目前为止,目的已经达到得到了SqlSession对象.通过调用SqlSession里面的方法,
             * 可以测试MyBatis和Dao层接口方法之间的正确性,当然也可以做别的很多事情,在这里就不列举了
             */
            //插入数据
            User user = new User();
            user.setC_password("123");
            user.setC_username("123");
            user.setC_salt("123");
            //第一个参数为方法的完全限定名:位置信息+映射文件当中的id
            session.insert("com.cn.dao.UserMapping.insertUserInformation", user);
            //提交事务
            session.commit();
            //关闭session
            session.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

针对上面的代码给出详细的说明关于SqlSessionFactory和SqlSession创建过程涉及的内容:

结合上述SqlSessionFactory和SqlSession使用过程和结构图,涉及到的方法为下面步骤,结合源码中的方法为下面的步骤:

第一步首先SqlSessionFactoryBuilder去读取mybatis的配置文件,然后build一个DefaultSqlSessionFactory,即得到SqlSessionFactory
 

//源码中涉及的包和具体方法为:
//涉及的包为:package org.apache.ibatis.session;

//第一个类为:SqlSessionFactoryBuilder,设计到此类的方法为下面部分:
public SqlSessionFactory build(InputStream inputStream) {
    return build(inputStream, null, null);
  }

public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
    try {
      //通过XMLConfigBuilder解析配置文件,解析的配置相关信息都会封装为一个Configuration对象
      XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
      //然后返回一个DefaultSqlSessionFactory
      return build(parser.parse());
    } catch (Exception e) {
      throw ExceptionFactory.wrapException("Error building SqlSession.", e);
    } finally {
      ErrorContext.instance().reset();
      try {
        inputStream.close();
      } catch (IOException e) {
        // Intentionally ignore. Prefer previous error.
      }
    }
  }

 //得到DefaultSqlSessionFactory
 public SqlSessionFactory build(Configuration config) {
   return new DefaultSqlSessionFactory(config);
 }

//第二个类为:DefaultSqlSessionFactory,涉及的方法为:
  public DefaultSqlSessionFactory(Configuration configuration) {
    this.configuration = configuration;
  }

第二步,获取到SqlSessionFactory之后,就可以利用SqlSessionFactory方法的openSession来获取SqlSession对象了。

private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
  Transaction tx = null;
  try {
    //通过Confuguration对象去获取Mybatis相关配置信息, Environment对象包含了数据源和事务的配置
    // execType为执行器类型,配置文件中定义
    // SimpleExecutor -- SIMPLE 就是普通的执行器。
    //ReuseExecutor -执行器会重用预处理语句(prepared statements)
    //BatchExecutor --它是批量执行器
    final Environment environment = configuration.getEnvironment();
    final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
    tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
    //定义执行器,是对statement的封装
    final Executor executor = configuration.newExecutor(tx, execType);
    //最后返回一个SqlSession
    return new DefaultSqlSession(configuration, executor, autoCommit);
  } catch (Exception e) {
    closeTransaction(tx); // may have fetched a connection so lets call close()
    throw ExceptionFactory.wrapException("Error opening session.  Cause: " + e, e);
  } finally {
    ErrorContext.instance().reset();
  }
}

得到SqlSession对象之后就可以利用SqlSession内部的方法进行CRUD操作了。

注意一点,Connection对象是在SqlSession对象创建之后进行CURD操作中创建的。深入查找之后找到在ManagedTransaction类中找到获取Connection对象的关键代码如下:

  protected void openConnection() throws SQLException {
    if (log.isDebugEnabled()) {
      log.debug("Opening JDBC Connection");
    }
    //dataSource 来源有三种,JndiDatasource,PooledDataSource,UnpooledDataSource,配置文件中定义
    this.connection = this.dataSource.getConnection();
    if (this.level != null) {
      this.connection.setTransactionIsolation(this.level.getLevel());
    }
  }

PooledDataSource和UnPooledDataSource的区别是PooledDataSource使用了连接池。为什么使用连接池呢?因为创建一个Connection对象的过程,在底层就相当于和数据库建立的通信连接,在建立通信连接的过程,消耗了非常多的时间,而往往我们建立连接后(即创建Connection对象后),就执行一个简单的SQL语句,然后就要抛弃掉,这是一个非常大的资源浪费!mybatis针对这一个问题提出的PooledDataSource使用了连接池。关于数据库连接池的知识点,可以自行百度,在这里就不扩展介绍了。

原创不易,转载自:MyBatis常用对象SqlSessionFactory和SqlSession介绍和运用_DemoTransfer-CSDN博客_sqlsessionfactory

Rust Reqwest+Rustls 自签名证书校验 所以这里必须保证reqwest引用的rustls库和本地工程一致。以上就是实现不校验签名的逻辑,后续自己可以在对应回调进行逻辑判断。 阅读详情

相关推荐

RoboMaster电控入门:手把手教你用STM32CubeMX配置大疆C板CAN总线驱动GM6020电机

本文详细介绍了如何使用STM32CubeMX配置大疆C板CAN总线驱动GM6020电机,适用于RoboMaster电控入门。从硬件准备到CubeMX工程初始化,再到CAN过滤器配置和电机控制协议解析,手把手教你避开常见配置陷阱,实现精准控制。

weixin_42524762的博客 274

mybatis:Creating a new SqlSession Closing non transactional SqlSession

Creating a new SqlSession SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@42607e80] was not registered for synchronization because synchronization is not active JDBC Connection [com.alibaba.druid.proxy.jdbc.ConnectionProxyImpl@56ebc6bb] w.

yzh_1346983557的博客 4万+

Optisystem软件与Matlab软件的联合数据读取

目录 Matlab软件程序编写 Optisystem软件的连接与设置 数据读取结果 Matlab软件程序编写 利用Matlab软件按照下图编写程序,保存为getdata.m文件。 OutputPort1 =InputPort1; fileID=fopen('OSAdata.txt','wt'); fprintf(fileID,'%f\n',OutputPort1.Sampled.Signal); fclose(fileID); Optisystem软件的连接与设置 (以基于线性插值法

Vivian_Chen_的博客 4858

SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@xxx] was not registered for synchro

Creating a new SqlSession SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@4218520b] was not registered for synchronization because synchronization is not active JDBC Connection [com.alibaba.druid.proxy.jdbc.ConnectionProxyImpl@affeb4e] wil

AVATAR 3万+

BIM模型导入SuperMap

目录 一、超图 BIM插件安装 1.1 插件下载 1.2 安装 二、BIM模型导出 2.1 Revit插件导出 2.2 SuperMap导入工具 三、SuperMap BIM数据处理与服务发布 四、SuperMap三维数据处理中关于模型高程修改方法 一、超图 BIM插件安装 1.1 插件下载 下载链接:http://support.supermap.com.cn/DownloadCenter/DownloadPage.aspx?tt=ProductAAS&id=134 1..

爱晒太阳的风 3615

(实测可用)STM32L431RCT6开发板-实验1 跑马灯实验

一、开发板平台简介: 1、开发板资源简介 (1)开发板主芯片型号:STM32L431RCT6 (2)开发板主芯片封装:LQFP-64_10x10x05P (3)开发板主芯片内核:ARM® Cortex®-M4 (4)开发板主芯片主频:80MHz (5)开发板主芯片Flash大小:256KB (6)开发板主芯片RAM大小:64KB

zhej2014的博客 3176

SqlSessionFactory介绍

SqlSessionFactory是MyBatis的关键字,它是单个数据库映射关系经过编译后的内存镜像,SqlSessionFactory对象的实例可以通过SqlSessionFactoryBuilder对象来获得,而SqlSessionFactoryBuildr则可以从XML配置文件或一个预先定制的Configuration的实例构建出SqlSessionFactory的实例 每一个MyBatis的应用程序都以一个SqlSessionFactory对象的实例为核心。SqlSessionFactory是线

weixin_45941064的博客 1万+

使用亚组分析进行子组分析并可视化森林图 - R语言

通过亚组分析和森林图的结合,我们可以更好地理解不同子组之间的差异和效果大小。当然,在实际应用中,还需要考虑多种因素,如样本量、异质性等,以得到更准确的结果和结论。每个森林图中的水平线代表了每个子组的效应估计,线的长度表示了该效应估计的置信区间。假设我们有一个包含研究对象的数据框(data frame),其中包括了治疗组和对照组的结果数据,以及一些可能的影响因素作为调整变量。在本例中,我们将比较两种不同的治疗方法(A和B)对结果变量的影响,并调整了一个额外的变量。是结果变量和对照组变量的列名。

2301_79326857的博客 1238

mybati-plus

mybatis_plus (1)测试 自动拼接sql语句 Creating a new SqlSession SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@3b48e183] was not registered for synchronization because synchronization is not active 2021-04-19 16:18:05.070 INFO 3268 --- [

csdn099的博客 359

手把手教你学Simulink——四开关 Buck‑Boost(FSBB)变换器的无缝模式切换仿真

本文详细介绍了四开关Buck-Boost(FSBB)变换器的Simulink仿真方法,重点解决模式切换时的直通风险和输出电压波动问题。通过统一电压PI控制、迟滞比较模式仲裁(Buck/Boost/Pass-Through)和200ns死区设计,实现了Vin从26V到22V变化时Vout稳定在12V±0.15V。关键步骤包括:搭建功率级电路、Stateflow模式判断、PI控制器输出占空比映射(Buck模式D≈Vo/Vin,Boost模式D≈1-Vo/Vin),以及带死区的PWM信号分配。仿真验证了切换过程中

MHD0815的博客 129

YOLO26涨点改进 | 检测头Head创新改进篇 | 利用DynamicConv高效动态卷积改进YOLO26检测头,DyHead通过增强检测头操作,轻量化改进、提高模型目标检测的精度

YOLO26作为新一代轻量化目标检测模型的代表,凭借精简的Backbone架构、高效的特征融合 Neck 设计,在实时检测场景(如嵌入式设备、边缘计算)中展现出优异的性能,成为工业落地与科研入门的优选模型。但在实际应用中,YOLO26原生检测头仍存在核心瓶颈:采用固定参数卷积核,无法根据输入特征的目标尺度、纹理差异动态调整卷积权重,导致多尺度目标适配不足、复杂背景下特征利用率低,且传统改进方案往往难以平衡“精度提升”与“轻量化”,要么精度提升有限,要么大幅增加参数量、拖累推理速度。

qq_36130719的博客 387

MyBatis SqlSessionFactory和SqlSession

MyBatis SqlSessionFactory和SqlSession 一,SqlSessionFactory Mybatis提供了构造器SqlSessionFactoryBuilder来生成SqlSessionFactory。 在 MyBatis 中,既可以通过读取配置的 XML 文件的形式生成 SqlSessionFactory,也可以通过Java代码生成 SqlSessionFactory。 推荐采用 XML 的形式,因为代码的方式在需要修改的时候会比较麻烦。 当配置了 XML 或者提供代码后,My

淮宁湾的博客 1245

从零玩转Vitis裸机开发:手把手教你创建、移植与实战优化

✅ Vitis裸机开发全流程✅ 中断系统配置技巧✅ 跨平台移植方法论✅ 性能优化实战经验研究FreeRTOS移植探索AMP(非对称多处理)架构学习使用Vitis Analyzer进行性能分析技术雷达:关注Xilinx最新推出的Vitis Unified IDE,其集成了更强大的调试和分析工具。立即动手实践吧!

QQ_778132974的博客 586

SqlSessionFactory和SqlSession详解

1.SqlSessionFactory是MyBatis的关键对象,它是个单个数据库映射关系经过编译后的内存镜像。2.SqlSessionFactory对象的实例可以通过SqlSessionFactoryBuilder对象类获得,而SqlSessionFactoryBuilder则可以从XML配置文件或一个预先定制的Configuration的实例构建出SqlSessionFactory的实例。3.每一个MyBatis的应用程序都以一个SqlSessionFactory对象的实例为核心。4.SqlSessio

qq_40776361的博客 6640

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

SqlSessionFactory与SqlSession

SqlSessionFactory是MyBatis的关键对象,它是个单个数据库映射关系经过编译后的内存镜像。2.SqlSessionFactory对象的实例可以通过SqlSessionFactoryBuilder对象类获得,而SqlSessionFactoryBuilder则可以从XML配置文件或一个预先定制的Configuration的实例构建出SqlSessionFactory的实例。3.每一个MyBatis的应用程序都以一个SqlSessionFactory对象的实例为核心。

qq_37436172的博客 1456

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

SqlSession和SqlSessionFactory

SqlSession:应用程序和数据库之间交互的一个单线程对象(非线程安全的),数据库的C、R、U、D及事务的处理接口,select | update | delete | insert | commit | rollback | close | flushStatements等 SqlSessionFactory:工厂设计模式,创建SqlSession的工厂。SqlSessionFactory是...

qq_42051526的博客 5334

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

最最常用的 SqlSessionFactory 和 SqlSession,你真的了解吗?

点击关注公众号,实用技术文章及时了解前言学习框架一个比较好的路径阅读源码。本文介绍的SqlSessionFactory和SqlSession。可以通过了解SqlSessionFactory接口和SqlSession接口以及两个的实现类入手,去看源码了解实现过程。最好能把项目下载到本地,慢慢分析实现过程。MyBatis的持久化解决方案是将用户从原始的JDBC访问中解放出来,...

Java知音 1278

MyBatis常用对象SqlSessionFactory和SqlSession介绍和运用

前言: 学习框架一个比较好的路径阅读源码.本文介绍的SqlSessionFactory和SqlSession.可以通过了解SqlSessionFactory接口和SqlSession接口以及两个的实现类入手,去看源码了解实现过程.最好能把项目下载到本地,慢慢分析实现过程. Myabtis官网:http://www.mybatis.org/ github地址:https://github.com/mybatis/mybatis-3 MyBatis的持久化解决方案是将用户从原始的JDBC访问中解.

lisheng19870305的专栏 949

SqlSessionFactory和SqlSession

1.SqlSessionFactory是MyBatis的关键对象,它是个单个数据库映射关系经过编译后的内存镜像。 2.SqlSessionFactory对象的实例可以通过SqlSessionFactoryBuilder对象类获得,而SqlSessionFactoryBuilder则可以从XML配置文件或一个预先定制的Configuration的实例构建出SqlSessionFactory的实例。

Pursuit_li的博客 160

MyBatis工厂类解析:SqlSessionFactory与SqlSession

在软件开发过程中,数据库操作是不可避免的环节。想象一下,一个程序员正坐在电脑前,面对着满屏的代码,眉头紧锁,手指在键盘上快速敲击。突然,他停下了手中的动作,双手抱胸,眼睛直勾勾地盯着屏幕,嘴里嘟囔着:“哟呵,这需求得去数据库里捞点数据出来。”以往,手动与数据库打交道,那可真是麻烦得很,各种连接配置、SQL语句,想想都让人头疼。然而,在这个困扰中,他突然想起了MyBatis。MyBatis是一个优秀的持久层框架,它消除了几乎所有的JDBC代码和手动设置参数以及获取结果集的过程。

MoneyHacksPro的博客 1074

【MyBatis 5】SqlSessionFactory和SqlSession

看完上述知识点如果你深感Java基础不够扎实,或者刷题刷的不够、知识不全面小编专门为你量身定制了一套针对知识面不够,也莫慌!还有一整套的,可以瞬间查漏补缺全都是一丢一丢的收集整理纯手打出来的。

2301_79655496的博客 1536

Mybatis——SqlSessionFactory与SqlSession原理

本博文主要介绍Mybatis中SqlSessionFactory与SqlSession原理。帮助大家更好的理解Mybatis的工作原理。

庄小焱 1828

一文彻底搞懂Mybatis系列(十)之SqlSession、SqlSessionFactory和SqlSessionFactoryBuilder详解

1、使用 MyBatis 的主要 Java 接口就是 SqlSession。你可以通过这个接口来执行命令,获取映射器示例和管理事务。在介绍 SqlSession 接口之前,我们先来了解如何获取一个 SqlSession 实例。SqlSessions 是由 SqlSessionFactory 实例创建的。SqlSessionFactory 对象包含创建 SqlSession 实例的各种方法。

weixin_43860634的博客 5444

Mybatis SqlSessionFactory和SqlSession

SqlSession是用来操作xml文件中sql语句,每次操作数据库我们都需要一个SqlSession对象SqlSession用来和数据库中的事务进行对接的,所以SqlSession里面包含了事务隔离级别等信息。SqlSession实例是线程不安全的,故最佳的请求范围是请求(request)或者方法(method)。SqlSession也是一个接口,有两个实现类:DefaultSqlSession和SqlSessionManager。...

weixin_45729272的博客 566
上一篇: 【Java基础知识 4】秒懂数组拷贝,感知新境界
下一篇: 【Java 代码实例 2】利用Java反射实现两个具有相同属性bean赋值
哪 吒
哪 吒 2022年度博客之星TOP 1 2022年度博客之星TOP 1 领域专家: 后端开发技术领域 领域专家: 后端开发技术领域
博客等级 码龄9年 59万+粉丝 2962原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址