Spring2.5教程:7、Spring+JDBC组合开发和事务

Spring JDBC事务管理 1.Spring JDBC的配置与JDBCTemplate对象 2.声明事务的配置方式 3.声明式事务的七种传播行为 1、Spring JDBC Spring JDBC是Spring框架用于处理关系型数据库的模块 Spring JDBC对JDBC aPI 进行封装,极大简化开发工作量 JDBCTemplate是Spring JDBC的核心类,提供数据的CRUD方法 为什么有了Mybatis还需要Spring JDBC? 答:Mybatis对JDBC的封装程度较高,Spring JD. 阅读详情

Spring+JDBC组合开发

 使用Spring+JDBC集成步骤如下:

l配置数据源,如:

 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">

    <property name="driverClassName" value="org.gjt.mm.mysql.Driver"/>

    <property name="url" value="jdbc:mysql://localhost:3306/itcast?useUnicode=true&amp;characterEncoding=UTF-8"/>

    <property name="username" value="root"/>

    <property name="password" value="123456"/>

     .....略

  </bean>

l配置事务。配置事务时,需要在xml配置文件中引入用于声明事务的tx命名空间(见下页),事务的配置方式有两种:注解方式和基于XML配置方式。

在spring配置文件中引入用于声明事务的tx命名空间

<beans xmlns="http://www.springframework.org/schema/beans"

       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

       xmlns:aop="http://www.springframework.org/schema/aop"

       xmlns:context="http://www.springframework.org/schema/context"

       xmlns:tx="http://www.springframework.org/schema/tx"

       xsi:schemaLocation="http://www.springframework.org/schema/beans

           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd

    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd

           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd

           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">

</beans>

配置数据源

 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">

    <property name="driverClassName" value="org.gjt.mm.mysql.Driver"/>

    <property name="url" value="jdbc:mysql://localhost:3306/itcast?useUnicode=true&amp;characterEncoding=UTF-8"/>

    <property name="username" value="root"/>

    <property name="password" value="123456"/>

     <!-- 连接池启动时的初始值 -->

   <property name="initialSize" value="1"/>

   <!-- 连接池的最大值 -->

   <property name="maxActive" value="500"/>

   <!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->

   <property name="maxIdle" value="2"/>

   <!--  最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来

不及申请 -->

   <property name="minIdle" value="1"/>

  </bean>

使用属性占位符方式配置数据源

也可以把上述的配置数据源写到.properties文件中,然后使用属性占位符方式加入到spring中,如下所示:

<context:property-placeholderlocation=“classpath:jdbc.properties”/>

其中 "classpath: " 表示从classpath的路径下搜索文件为jdbc.properties的文件,然后就可以在Spring的配置文件中这样引用:

<context:property-placeholder location=“classpath:jdbc.properties”/>

 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">

   <property name="driverClassName" value="${driverClassName}"/>

    <property name="url" value="${url}"/>

    <property name="username" value="${username}"/>

    <property name="password" value="${password}"/>

     <!-- 连接池启动时的初始值 -->

   <property name="initialSize" value="${initialSize}"/>

   <!-- 连接池的最大值 -->

   <property name="maxActive" value="${maxActive}"/>

   <!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->

   <property name="maxIdle" value="${maxIdle}"/>

   <!--  最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->

   <property name="minIdle" value="${minIdle}"/>

  </bean>

 

采用注解方式配置事务

l采用注解方式

<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager>

   <!--将dataSource对象注入到spring的事务管理类中-->

    <property name="dataSource" ref="dataSource"/>

  </bean>

 <!– 采用@Transactional注解方式使用事务(必须加入tx名字空间)  -->

  <tx:annotation-driven transaction-manager="txManager"/>

配置好后就可以在程序中使用@Transactional来申明事务

@Service @Transactional

public class PersonServiceBean implements PersonService {

}

@Transactional也可以只运行在方法上

 

采用基于XML方式配置事务

<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

    <property name="dataSource" ref="dataSource"/>

</bean>

<aop:config>

    <aop:pointcut id="transactionPointcut" expression="execution(*    

                                                                           cn.itcast.service..*.*(..))"/>

    <aop:advisor advice-ref="txAdvice" pointcut-ref="transactionPointcut"/>

</aop:config>

<tx:advice id="txAdvice" transaction-manager="txManager">

    <tx:attributes> <!--以get开始的方法不要事务-->

      <tx:method name="get*" read-only="true" propagation="NOT_SUPPORTED"/>

      <tx:method name="*"/><!--启用默认事务行为,数据库默认级别-->

    </tx:attributes>

</tx:advice>

 

使用JdbcTemplate进行insert/update/delete操作

@Service @Transactional

public class PersonServiceBean implements PersonService {

  private JdbcTemplatejdbcTemplate;

  @Resource

  public void setDataSource(DataSourcedataSource) {

      this.jdbcTemplate = new JdbcTemplate(dataSource);

  }

    //添加

  public void save(Person person) throws Exception{

  jdbcTemplate.update("insert into person (name) values(?)",

  new Object[]{person.getName()}, new int[]{java.sql.Types.VARCHAR});

  }

}

使用JdbcTemplate获取一条记录

@Service @Transactional

public class PersonServiceBean implements PersonService {

  private JdbcTemplatejdbcTemplate;

  @Resource

  public void setDataSource(DataSourcedataSource) {

      this.jdbcTemplate = new JdbcTemplate(dataSource);

  }

   public Person getPerson(Integer id){

  RowMapperrowMapper = new RowMapper(){

  public Object mapRow(ResultSetrs, introwNum) throws SQLException {

  Person person = new Person();

  person.setId(rs.getInt("id"));

  person.setName(rs.getString("name"));

  return person;

  }

  };

  return (Person)jdbcTemplate.queryForObject("select * from person where id=?",

  new Object[]{id}, new int[]{java.sql.Types.INTEGER}, rowMapper);

  }}

使用JdbcTemplate获取多条记录

@Service @Transactional

public class PersonServiceBean implements PersonService {

  private JdbcTemplatejdbcTemplate;

  @Resource

  public void setDataSource(DataSourcedataSource) {

      this.jdbcTemplate = new JdbcTemplate(dataSource);

  }

  public List<Person> getPersons(){

  RowMapperrowMapper = new RowMapper(){

  public Object mapRow(ResultSetrs, introwNum) throws SQLException {

  Person person = new Person();

  person.setId(rs.getInt("id"));

  person.setName(rs.getString("name"));

  return person;

  }

  };

  return jdbcTemplate.query("select * from person", rowMapper);

  }

}

 

事务传播属性

REQUIRED:业务方法需要在一个事务中运行。如果方法运行时,已经处在一个事务中,那么加入到该事务,否则为自己创建一个新的事务。(默认)

NOT_SUPPORTED:声明方法不需要事务。如果方法没有关联到一个事务,容器不会为它开启事务。如果方法在一个事务中被调用,该事务会被挂起,在方法调用结束后,原先的事务便会恢复执行。

REQUIRESNEW:属性表明不管是否存在事务,业务方法总会为自己发起一个新的事务。如果方法已经运行在一个事务中,则原有事务会被挂起,新的事务会被创建,直到方法执行结束,新事务才算结束,原先的事务才会恢复执行。

MANDATORY:该属性指定业务方法只能在一个已经存在的事务中执行,业务方法不能发起自己的事务。如果业务方法在没有事务的环境下调用,容器就会抛出例外。

SUPPORTS:这一事务属性表明,如果业务方法在某个事务范围内被调用,则方法成为该事务的一部分。如果业务方法在事务范围外被调用,则方法在没有事务的环境下执行。

Never:指定业务方法绝对不能在事务范围内执行。如果业务方法在某个事务中执行,容器会抛出例外,只有业务方法没有关联到任何事务,才能正常执行。

NESTED:如果一个活动的事务存在,则运行在一个嵌套的事务中. 如果没有活动事务, 则按REQUIRED属性执行.它使用了一个单独的事务,这个事务拥有多个可以回滚的保存点。内部事务的回滚不会对外部事务造成影响。它只对DataSourceTransactionManager事务管理器起效

spring的事务

spring的事务默认在运行时异常时回滚,在编译异常不回滚,

public void deletePerson(int id) {

  jdbcTemplate.update("delete from person where id=?".......)

  throw new RuntimeExcepton();

  }程序会回滚。

public void deletePerson(int id) throws Exception {

  jdbcTemplate.update("delete from person where id=?".......)

  throw new Excepton();

}不会回滚

要使用发生编译期异常时回滚,可以指定@Transactional的rollbackFor=Excepton.class

@Transactional(rollbackFor=Excepton.classs)

public void deletePerson(int id) throws Exception {

  jdbcTemplate.update("delete from person where id=?".......)

  throw new Excepton();

}

要指定spring的事务传播属性,可以设置 Transactional(propagation=Propagation.XXX)

其中XXX表示上页的事务传播属性

当进行查询时可以把事务设置成只读事务。readOnly="true"

事务传播属性NESTED介绍

@Resource OtherService otherService

public void xxx() {

  stmt.exectuteUpdate("update person set name='888' where id=1");

  otherService.update();//OtherService的update方法的事务传播属性为NESTED

  stmt.executeUpdate("delete from person where id=9");

下一页则是对此程序的解释

Connection conn = null;

try {

    conn.setAutoCommit(false);

    Statement stmt = conn.createStatement();

    stmt.executeUpdate("update person set name='888' where id=1");

    Savepointsavepoint = conn.setSavepoint();

    try{  

            conn.createStatement().executeUpdate("update person set name='222' where sid=2");

    }catch(Exception ex){

            conn.rollback(savepoint);   

     }

      stmt.executeUpdate("delete from person where id=9");

      conn.commit();

       stmt.close();

    } catch (Exception e) {

         conn.rollback();

     }finally{

               try {

      if(null!=conn && !conn.isClosed()) conn.close();

                } catch (SQLException e) { e.printStackTrace(); }

     }

}

数据库系统提供了四种事务隔离级

数据库系统提供了四种事务隔离级别供用户选择。不同的隔离级别采用不同的锁类型来实现,在四种隔离级别中,Serializable的隔离级别最高,Read Uncommited的隔离级别最低。大多数据库默认的隔离级别为Read Commited,如SqlServer,当然也有少部分数据库默认的隔离级别为Repeatable Read ,如Mysql

lRead Uncommited:读未提交数据(会出现脏读,不可重复读和幻读)。
lRead Commited:读已提交数据(会出现不可重复读和幻读)
lRepeatable Read:可重复读(会出现幻读)
lSerializable:串行化

脏读:一个事务读取到另一事务未提交的更新新据。

不可重复读:在同一事务中,多次读取同一数据返回的结果有所不同。换句话说就是,后续读取可以读到另一事务已提交的更新数据。相反,“可重复读”在同一事务中多次读取数据时,能够保证所读数据一样,也就是,后续读取不能读到另一事务已提交的更新数据。

幻读:一个事务读取到另一事务已提交的insert数据。

 

Spring JDBC和事务管理 Spring JDBC是Spring框架用来处理关系型数据库的模块,对JDBC的API进行了封装。Spring JDBC的核心类为JdbcTemplate,提供数据CRUD方法。 阅读详情

相关推荐

CoppeliaSim(原V-REP)新手上路

CoppeliaSim(原V-REP)是一个机器人仿真平台,里面有很多来自别的公司的机器人模型以及完备的物理引擎,我们可以通过python,c++,matlab等语言控制里面的机器人。,您也可以在官网中Downloads里找您需要的版本,一般只需要下载EDU版本就可以了,我下载的是v4.1.0 windows EDU版本。在版本V4之前,CoppeliaSim叫V-REP,在官网可以下载到之前的V-REP版本。

qq_37051669的博客 4万+

使用spring2.5.6整合jdbc的基本配置

以下是使用spring2.5.6整合jdbc时,配置文件applicationContext.xml的写法 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"  xmlns:aop="http://www.springfram

黄俊东的专栏 1623

机器学习【学校智慧食堂及其应用】

本文主要介绍机器学习【智慧食堂及其应用】

qq_201729558 2571

为什么在Spring的配置里,最好不要配置xsd文件的版本号

为什么dubbo启动没有问题? 这篇blog源于一个疑问: 我们公司使了阿里的dubbo,但是阿里的开源网站http://code.alibabatech.com,挂掉有好几个月了,为什么我们的应用启动没有问题? 我们的应用的Spring配置文件里有类似的配置:   &lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns...

横云断岭的专栏 6万+

Unity Spine动画控制全攻略:播放、回调与停止的实战技巧

本文深入解析Unity中Spine动画的核心控制技巧,涵盖动画播放、轨道分层、事件回调与平滑停止等实战方法。通过封装SpineAnimationController,详细讲解了如何利用动画播放结束回调实现精准的游戏逻辑同步,并提供了避免内存泄漏和动画卡顿的避坑指南,助力开发者打造流畅专业的2D游戏动画系统。

weixin_29021291的博客 378

RT-Thread新手必看:FMT飞控移植中的5个常见坑及解决方案

本文针对RT-Thread新手在移植FMT开源飞控时遇到的5大核心挑战,提供了深度解决方案。内容涵盖SCons构建系统配置、RT-Thread版本API兼容性处理、BSP与设备驱动适配、TOML系统配置解析以及算法模块集成调试,帮助开发者高效避坑,成功完成飞控移植。

gin88的博客 250

Spring基础知识1:spring2.5与jdbc整合demo

好久没写jdbc的相关代码了,都忘得差不多了,一直都在用hibernate,这次学习spring,书中有关于jdbc整合的章节,并且讲了很多,于是决定再次写有关jdbc代码。整个写的非常简单,具体如下:   第一步:引入相关的jar包 第二步:在spring中配置好数据源(bean.xml) &lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt...

hyj956948933的专栏 167

CS231n+assignment2(一)

cs231n作业二详解+代码

qq_56551150的博客 2411

Spring JDBC和事务控制

​ Spring 框架除了提供 IOC 与 AOP 核心功能外,同样提供了基于JDBC 的数据访问功能,使得访问持久层数据更加方便。想要使用 Spring JDBC 环境,需要将JDBC整合到Spring中。构建项目:普通的java项目即可 添加 jdbc 配置文件 在src/main/resources目录下新建db.properties配置文件,并设置对应的配置信息放在配置文件的目的:后续修改的时候直接到配置文件中修改即可。 以下为可选配置 编写 spring 配置文件 编写spring配置文件:app

持续学习,持续更新 2707

学Simulink--环境感知场景实例:基于Simulink的毫米波雷达多目标跟踪仿真

本文介绍了基于Simulink的毫米波雷达多目标跟踪仿真系统,重点分析了FMCW雷达信号处理流程(Range/Doppler FFT、CFAR检测)和多目标跟踪算法(JPDA数据关联、EKF状态估计)。通过构建城市道路交叉场景,验证了系统在跟踪精度(位置误差<0.2m)、实时性(单帧处理24ms)和鲁棒性(ID切换率<5%)方面的性能优势,并提出了UKF滤波、多传感器融合等优化方向。该仿真系统为自动驾驶环境感知提供了实用的毫米波雷达跟踪解决方案。

amy_mhd的博客 92

Qt C++ 的虚拟演播室系统

**数据流转**:OpenCV 处理的图像格式通常是 `cv::Mat`,而 Qt 3D 渲染需要 `QImage` 或 `QTexture2D`。// 临时用颜色代替。// 前景在背景前面。#### 3.3 主窗口与 Qt 3D 集成 (`mainwindow.h` / `.cpp` / `.ui`)* **更复杂的 3D 场景**:加载 3D 模型(.obj, .gltf 等)作为背景和道具。1. **构建项目**:确保 `.pro` 文件中的 OpenCV 路径配置正确,然后构建项目。

寒寒豆豆软件公司的博客 111

spring中的JDBC和spring事务

Spring JDBC是Spring所提供的持久层技术,负责数据库资源和错误处理,降低JDBC API的使用难度,以一种更简洁,更直接的方式使用JDBC API,大大简化了开发人员对数据库的操作。JdbcTemplate是spring框架中提供的一个对象,是对原始繁琐的Jdbc API对象的简单封装。spring框架为我们提供了很多的操作模板类。JdbcTemplate虽然简单,功能却非常强大。

t2786024916的博客 913

32、社交媒体大数据中的情感分析与网络欺凌检测

本文探讨了社交媒体大数据在情感分析和网络欺凌检测中的应用。情感分析有助于应对自动化带来的社会变化、促进社会包容和推动环境保护。网络欺凌作为一种严重的在线危害,其检测依赖于数据预处理、特征提取与深度学习模型(如CNN、LSTM)进行分类。文章还总结了大数据在欺诈检测、医疗、制造、交通等领域的广泛应用,并分析了数据存储、处理速度、质量和技术工具等方面的挑战,提出了相应的应对策略。未来,随着技术进步,社交媒体大数据将在更多领域发挥关键作用。

cc789的博客 91

Spring5源码之JDBC事务

这篇文章主要介绍了Spring5源码之JDBC事务,通过源码剖析Spring5对事物是如何处理的,需要的朋友可以参考一下。 1、annotation-driven 根据配置文件annotation-driven关键字,定位到代码最终锁定类TxNamespaceHandler,在TxNamespaceHandler类中的init方法。 @Override public void init() { registerBeanDefinitionParser("advice", new TxAdviceBea.

shanjian341622的博客 383

深度学习工具包 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")

STM32F407中文手册

STM32f407中文手册 本参考手册面向应用开发人员,提供有关使用 STM32F405xx/07xx、STM32F415xx/17xx、 STM32F42xxx 和 STM32F43xxx 微控制器存储器与外设的完整信息。STM32F405xx/07xx、STM32F415xx/17xx、STM32F42xxx 和 STM32F43xxx 构成一个微 控制器系列,各产品具有不同的存储器大小、封装和外设。有关订购信息以及器件的机械与电气特性,请参见数据手册。有关 ARM Cortex™-M4F 内核的信息,请参见《Cortex™-M4F 技术参考手册》。

Spring+JDBC组合开发/Spring事务管理简介

使用Spring+JDBC集成步骤如下:l         需要的jar包:Spring相关包:commons-annotations.jar、commons-logging.jarJDBC驱动jar包数据源jar包:commons-dbcp.jar、commons-pool.jarl         配置数据源,如:l         配置事务:配置事务时,需要中

希望与大家交流程序设计经验 1106

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

Spring JDBC 与数据访问:从性能优化到事务协同

Spring JDBC 与数据访问:从性能优化到事务协同

weixin_46619605的博客 1767

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

【小家Spring】Spring-jdbc的使用以及Spring事务管理的8种方式介绍(声明式事务+编程式事务)

前言 前面已经讲述了Spring Aop的原理以及源码分析~ 若对Spring AOP还不是太了解的话,强烈建议出门左拐,先掌握AOP相关内容,因为Spring的事务管理就是基于Spring AOP实现的 本文主要讲解Spring-JDBC的使用以及它对事务的管理。 主要分为两大块: Spring对JDBC的支持 Spring对事务的支持 环境准备 Pom里导入相关jar: ...

架构师:通透,才能写出好代码! 2580

Spring JDBC与事务管理5:Spring编程式事务;

说明: (1)有关事务内容可以快速参考【MySQL综合应用二:事务机制一:事务的基本介绍】附近文章,【JDBC入门九:JDBC实现事务(十分重要!!!)】; (2)

小枯林的博客 876

Spring JDBC及声明式事务

Spring JDBC 封装了原生的JDBC API,使得处理关系型数据库更加简单。Spring JDBC的核心是JdbcTemplate,里面封装了大量数据库CRUD的操作。使用Spring JDBC有如下步骤:1、pom增加依赖spring-context是spring的核心,负责容器中对象实例创建;spring-jdbc是对原生jdbc的封装;logback-classic主要为了数据库操作时辅助信息的日志输出。2、IOC容器实例化数据源对象dataSource和JdbcTemplate对象。

xujinwei_gingko的专栏 1236

Jdbc事务以及Spring事务解惑

一、引言 Spring是一个IOC框架,在此IOC框架的基础上,提供了DAO集成,AOP事务控制,JNDI等等一系列的高级功能,个人觉得,在Spring中最值得称道的不仅仅他是一个非入侵的IOC容器,而在于其神奇的声明事务以及异常处理; 二、Jdbc事务实现 为什么要使用事务,银行转账的例子都用烂了,这里就不再累赘,JDBC的本地事务利用Connention.setAutoCom

辉悦天成的专栏 798

Spring5整合JDBC事务的使用案例

这篇文章主要介绍了Spring5整合JDBC事务的使用案例,通过案例来了解Spring5与JDBC事务的结合,需要的朋友可以参考一下。 Spring声明式事务让我们从复杂的事务处理中得到解脱,使我们再也不需要去处理获得连接、关闭连接、事务提交和回滚等操作,再也需要与事务相关方法处理大量的try…catch…finally代码。Spring中事务的使用虽然已经相对简单得多,但是还是有很多的使用及配置规则。这里只列举简单的使用方法。 1、创建数据库表结构 DROP TABLE IF EXISTS `user.

shanjian341622的博客 400

Spring入门04-Spring JDBC 和 事务控制

例2(同样的条件, 第1次和第2次读出来的记录数不一样 ):假某工资单表中工资大于3000的有4人,事务1读取了所有工资大于3000的人,共查到4条记录,这时事务2又插入了一条工资大于3000的记录,事务1再次读取时查到的记录就变为了5条,这样就导致了幻读。事务(Transaction)指的是一个操作序列,该操作序列中的多个操作要么都做,要么都不做,是一个不可分割的工作单位,是数据库环境中的逻辑工作单位,由DBMS中的事务管理子系统负责事务的处理。并且其他的事务对于转账操作的事务是不能产生任何影响的。

YiGeFive的博客 583

Spring JDBC 和事务控制

Spring JDBC 和 事务控制

weixin_67969747的博客 1068

【Spring Boot】事务和事务传播机制

将一组操作封装成一个执行单元,要么全部成功,要么全部失败。当执行某个操作,例如支付操作时(分为先将钱从个人账户扣除和将他人账户新增两个操作),如果这两个操作不能同时成功或者失败,那么就会出现财产问题。而使用事务就能够很好的解决这个问题。通过上文我们了解到,在需要的方法上添加 @Transactional 注解,就能自动开启事务。接下来将会具体了解下 @Transactional 的使用细节。Spring 事务传播机制定义了多个包含了事务的方法在相互调用时,事务是如何在这些方法之间进行传递的。...

吞吞吐吐大魔王的博客 3853

【回顾原生JDBC手动管理事务以及两种方式实现Spring编程式事务】

了解原生JDBC手动管理事务、Spring编程式事务,对我们学习Spring声明式事务,分布式事务还是有很大帮助的~

weixin_44585177的博客 1717

Spring JDBC 和 事务控制

Spring JDBC 和 事务控制 主要内容 Spring 整合 JDBC 环境 ​ Spring 框架除了提供 IOC 与 AOP 核心功能外,同样提供了基于JDBC 的数据访问功能,使得访问持久层数据更加方便。使用 Spring JDBC 环境,首先需要一套 Spring 整合 JDBC 的环境。 添加依赖坐标 <!-- 添加相关的依赖坐标 --> <!-- spring 框架坐标依赖添加 --> <dependency> <groupId>o.

xyx12321的博客 404
上一篇: Spring2.5教程:6、AOP
下一篇: JDBC详解
风云才智
博客等级 码龄14年 46粉丝 48原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值