1 Spring中加入DataSource并引入jdbc.properties
- 步骤:
- ①加入c3p0的jar包和mysql的驱动包
- ②在src下新建jdbc.propertes文件
jdbc.driverClass=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/spring jdbc.user=root jdbc.password=root
- ③在applicationContext.xml中配置加载jdbc.properties的类
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd"> <!-- 配置加载jdbc.properties的类 --> <context:property-placeholder location="classpath*:jdbc.properties"></context:property-placeholder> <!-- 配置c3p0连接池 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${jdbc.driverClass"/> <property name="jdbcUrl" value="${jdbc.url}"/> <property name="user" value="${jdbc.user}"/> <property name="password" value="${jdbc.password}"/> </bean> </beans>
2 Spring jdbcTemplate
- Spring的jdbc Template使用的是模板技术。
- 观察如下代码的结构:
- jdbcDaoSupport.java
- jdbcTemplate.java
- jdbcAccessor.java
- 我们可以得出如下的规律
- 看看Hibernate是不是也这样:
- HibernateDaoSupport.java
- 示例:使用Spring的jdbc Template来实现CRUD
- dao层
- PersonDao.java
- dao层
package com.xuweiwei.dao; import java.sql.ResultSet; public interface PersonDao { public static final String DAO_NAME = "com.xuweiwei.dao.impl.PersonDaoImpl"; /** * 增加 * @param sql */ public void save(String sql); /** * 删除 */ public void delete(String sql); public void update(String sql); }
- PersonDaoImpl.java
package com.xuweiwei.dao.impl; import com.xuweiwei.dao.PersonDao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.jdbc.core.support.JdbcDaoSupport; import org.springframework.stereotype.Repository; import javax.annotation.Resource; import javax.sql.DataSource; import java.sql.ResultSet; @Repository(PersonDao.DAO_NAME) public class PersonDaoImpl extends JdbcDaoSupport implements PersonDao { @Resource(name = "dataSource") public void setDataSourcePerson(DataSource dataSource){ super.setDataSource(dataSource); } @Override public void save(String sql) { this.getJdbcTemplate().execute(sql); } @Override public void delete(String sql) { this.getJdbcTemplate().execute(sql); } @Override public void update(String sql) { this.getJdbcTemplate().execute(sql); } }
- service层
- PersonService.java
- service层
package com.xuweiwei.service; public interface PersonService { public static final String SERVICE_NAME = "com.xuweiwei.service.impl.PersonServiceImpl"; /** * 增加 * @param sql */ public void save(String sql); /** * 删除 */ public void delete(String sql); public void update(String sql); }
- PersonServiceImpl.java
package com.xuweiwei.service.impl; import com.xuweiwei.dao.PersonDao; import com.xuweiwei.service.PersonService; import org.springframework.stereotype.Service; import javax.annotation.Resource; @Service(PersonService.SERVICE_NAME) public class PersonServiceImpl implements PersonService { @Resource(name=PersonDao.DAO_NAME) private PersonDao personDao; @Override public void save(String sql) { personDao.save(sql); } @Override public void delete(String sql) { personDao.delete(sql); } @Override public void update(String sql) { personDao.update(sql); } }
- applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd"> <!-- 配置加载jdbc.properties的类 --> <context:property-placeholder location="classpath*:jdbc.properties"></context:property-placeholder> <!-- 配置c3p0连接池 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${jdbc.driverClass}"/> <property name="jdbcUrl" value="${jdbc.url}"/> <property name="user" value="${jdbc.user}"/> <property name="password" value="${jdbc.password}"/> </bean> <context:component-scan base-package="com.xuweiwei"/> </beans>
- 测试
package com.xuweiwei.test; import com.xuweiwei.service.PersonService; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestJdbcTemplate { @Test public void add(){ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); PersonService personService = (PersonService) context.getBean(PersonService.SERVICE_NAME); String sql = " insert into student(name,description) values ('许威威','java开发') "; personService.save(sql); } @Test public void update(){ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); PersonService personService = (PersonService) context.getBean(PersonService.SERVICE_NAME); String sql = " update student set description ='Linux开发' where sid = 1 "; personService.update(sql); } @Test public void delete(){ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); PersonService personService = (PersonService) context.getBean(PersonService.SERVICE_NAME); String sql = " delete from student where sid = 1 "; personService.delete(sql); } }
3 Spring的事务控制
3.1 引入Spring的事务控制
- 如果在上面的代码中,加入如下的代码
@Override public void save(String sql) { personDao.save(sql); int a = 1 /0 ; personDao.save(sql); }
- 会发现当发生异常的时候,事务并没有回滚,我们可以通过查看数据库知道,已经插入了一条数据。但是,这显示是不符合实际的,所以,Spring给我们提供了对事务的控制,当前表现形式不同,其实原理是一样的。
3.2 声明式事务
3.2.1 事务管理器
- Spring对不同的技术实现提供了不同的事务管理器,当然,如果我们自己去写一个框架,那么要和Spring整合,也需要遵守Spring的规则。
- Spring提供了一个PlatformTransactionManager的接口,详细代码如下
// // Source code recreated from a .class file by IntelliJ IDEA // (powered by Fernflower decompiler) // package org.springframework.transaction; public interface PlatformTransactionManager { TransactionStatus getTransaction(TransactionDefinition var1) throws TransactionException; void commit(TransactionStatus var1) throws TransactionException; void rollback(TransactionStatus var1) throws TransactionException; }
- PlatformTransactionManager接口有一个抽象实现类是AbstractPlatformTransactionManager,其简化代码如下
public abstract class AbstractPlatformTransactionManager implements PlatformTransactionManager, Serializable { public final TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException { Object transaction = this.doGetTransaction(); } protected abstract Object doGetTransaction() throws TransactionException; public final void rollback(TransactionStatus status) throws TransactionException { if (status.isCompleted()) { throw new IllegalTransactionStateException("Transaction is already completed - do not call commit or rollback more than once per transaction"); } else { DefaultTransactionStatus defStatus = (DefaultTransactionStatus)status; this.processRollback(defStatus); } } public final void commit(TransactionStatus status) throws TransactionException { if (status.isCompleted()) { throw new IllegalTransactionStateException("Transaction is already completed - do not call commit or rollback more than once per transaction"); } else { DefaultTransactionStatus defStatus = (DefaultTransactionStatus)status; if (defStatus.isLocalRollbackOnly()) { if (defStatus.isDebug()) { this.logger.debug("Transactional code has requested rollback"); } this.processRollback(defStatus); } else if (!this.shouldCommitOnGlobalRollbackOnly() && defStatus.isGlobalRollbackOnly()) { if (defStatus.isDebug()) { this.logger.debug("Global transaction is marked as rollback-only but transactional code requested commit"); } this.processRollback(defStatus); if (status.isNewTransaction() || this.isFailEarlyOnGlobalRollbackOnly()) { throw new UnexpectedRollbackException("Transaction rolled back because it has been marked as rollback-only"); } } else { this.processCommit(defStatus); } } } }
- DataSourceTransManager.java
public class DataSourceTransactionManager extends AbstractPlatformTransactionManager implements ResourceTransactionManager, InitializingBean { protected Object doGetTransaction() { DataSourceTransactionManager.DataSourceTransactionObject txObject = new DataSourceTransactionManager.DataSourceTransactionObject(); txObject.setSavepointAllowed(this.isNestedTransactionAllowed()); ConnectionHolder conHolder = (ConnectionHolder)TransactionSynchronizationManager.getResource(this.dataSource); txObject.setConnectionHolder(conHolder, false); return txObject; } }
- 示例:
- PersonDao.java
package com.xuweiwei.dao; public interface PersonDao { /** * 增加 * @param sql */ public void save(String sql); /** * 删除 */ public void delete(String sql); public void update(String sql); }
- PersonDaoImpl.java
package com.xuweiwei.dao.impl; import com.xuweiwei.dao.PersonDao; import org.springframework.jdbc.core.support.JdbcDaoSupport; public class PersonDaoImpl extends JdbcDaoSupport implements PersonDao { @Override public void save(String sql) { this.getJdbcTemplate().execute(sql); } @Override public void delete(String sql) { this.getJdbcTemplate().execute(sql); } @Override public void update(String sql) { this.getJdbcTemplate().execute(sql); } }
- PersonService.java
package com.xuweiwei.service; public interface PersonService { /** * 增加 * @param sql */ public void save(String sql); /** * 删除 */ public void delete(String sql); public void update(String sql); }
- PersonServiceImpl.java
package com.xuweiwei.service.impl; import com.xuweiwei.dao.PersonDao; import com.xuweiwei.service.PersonService; public class PersonServiceImpl implements PersonService { private PersonDao personDao; public void setPersonDao(PersonDao personDao) { this.personDao = personDao; } @Override public void save(String sql) { personDao.save(sql); int a = 1 /0 ; personDao.save(sql); } @Override public void delete(String sql) { personDao.delete(sql); } @Override public void update(String sql) { personDao.update(sql); } }
- jdbc.properties
jdbc.driverClass=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/spring jdbc.user=root jdbc.password=root
- applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd"> <!-- 配置加载jdbc.properties的类 --> <context:property-placeholder location="classpath*:jdbc.properties"></context:property-placeholder> <!-- 配置c3p0连接池 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${jdbc.driverClass}"/> <property name="jdbcUrl" value="${jdbc.url}"/> <property name="user" value="${jdbc.user}"/> <property name="password" value="${jdbc.password}"/> </bean> <bean id="personDao" class="com.xuweiwei.dao.impl.PersonDaoImpl"> <property name="dataSource" ref="dataSource"/> </bean> <bean id="personService" class="com.xuweiwei.service.impl.PersonServiceImpl"> <property name="personDao" ref="personDao"/> </bean> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <tx:advice id="tx" transaction-manager="transactionManager"> <!-- 告诉spring容器什么样的目标方法采用什么样的事务策略 name 用来说明目标方法 save* 以save开头的目标方法 isolation 隔离属性 propagation 传播属性 是解决事务嵌套问题的 read-only 为true:只读事务 只能读 为false:读写事务 --> <tx:attributes> <tx:method name="save*" isolation="DEFAULT" propagation="REQUIRED" read-only="false" /> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="pointcut" expression="execution(* com.xuweiwei.service.impl.PersonServiceImpl.*(..))"/> <aop:advisor advice-ref="tx" pointcut-ref="pointcut"/> </aop:config> </beans>
- 测试
package com.xuweiwei.test; import com.xuweiwei.service.PersonService; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestJdbcTemplate { @Test public void add(){ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); PersonService personService = (PersonService) context.getBean("personService"); String sql = " insert into student(name,description) values ('许威威','java开发') "; personService.save(sql); } }
3.3 编程式事务
- PersonDao.java
package com.xuweiwei.dao; public interface PersonDao { public static final String DAO_NAME = "com.xuweiwei.dao.impl.PersonDaoImpl"; /** * 增加 * @param sql */ public void save(String sql); /** * 删除 */ public void delete(String sql); public void update(String sql); }
- PersonDaoImpl.java
package com.xuweiwei.dao.impl; import com.xuweiwei.dao.PersonDao; import org.springframework.jdbc.core.support.JdbcDaoSupport; import org.springframework.stereotype.Repository; import javax.annotation.Resource; import javax.sql.DataSource; @Repository(PersonDao.DAO_NAME) public class PersonDaoImpl extends JdbcDaoSupport implements PersonDao { @Resource(name="dataSource") public void setDataSourceDi(DataSource dataSource){ super.setDataSource(dataSource); } @Override public void save(String sql) { this.getJdbcTemplate().execute(sql); } @Override public void delete(String sql) { this.getJdbcTemplate().execute(sql); } @Override public void update(String sql) { this.getJdbcTemplate().execute(sql); } }
- PersonService.java
package com.xuweiwei.service; public interface PersonService { public static final String SERVICE_NAME = "com.xuweiwei.service.impl.PersonServiceImpl"; /** * 增加 * @param sql */ public void save(String sql); /** * 删除 */ public void delete(String sql); public void update(String sql); }
- PersonServiceImpl.java
package com.xuweiwei.service.impl; import com.xuweiwei.dao.PersonDao; import com.xuweiwei.service.PersonService; import org.springframework.stereotype.Repository; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; @Transactional @Service(PersonService.SERVICE_NAME) public class PersonServiceImpl implements PersonService { @Resource(name=PersonDao.DAO_NAME) private PersonDao personDao; @Override public void save(String sql) { personDao.save(sql); int a = 1 /0 ; personDao.save(sql); } @Override public void delete(String sql) { personDao.delete(sql); } @Override public void update(String sql) { personDao.update(sql); } }
- jdbc.properties
jdbc.driverClass=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/spring jdbc.user=root jdbc.password=root
- applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd"> <!-- 配置加载jdbc.properties的类 --> <context:property-placeholder location="classpath*:jdbc.properties"></context:property-placeholder> <!-- 配置c3p0连接池 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${jdbc.driverClass}"/> <property name="jdbcUrl" value="${jdbc.url}"/> <property name="user" value="${jdbc.user}"/> <property name="password" value="${jdbc.password}"/> </bean> <context:property-placeholder location="classpath*:jdbc.properties"/> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!-- 开启编程式事务 --> <tx:annotation-driven transaction-manager="transactionManager"/> </beans>
- 测试
package com.xuweiwei.test; import com.xuweiwei.service.PersonService; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestJdbcTemplate { @Test public void add(){ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); PersonService personService = (PersonService) context.getBean("personService"); String sql = " insert into student(name,description) values ('许威威','java开发') "; personService.save(sql); } }
Spring 4.x (三)的更多相关文章
-
spring与mybatis三种整合方法
spring与mybatis三种整合方法 本文主要介绍Spring与Mybatis三种常用整合方法,需要的整合架包是mybatis-spring.jar,可通过链接 http://code.googl ...
-
MyEclipse Spring 学习总结三 SpringMVC
MyEclipse Spring 学习总结三 SpringMVC 一.SpringMVC原理 1.Springmvc 框架介绍 1)Spring 框架停工了构建Web应用程序的全功能MVC模块.Spr ...
-
Spring学习总结三——SpringIOC容器三
一:spring容器自动装配注入 为了减少xml中配置内容,可以使用自动装配注入,代替setter注入,只需要在 bean对象配置中添加属性autoWire即可,那么在类中就会自动扫描setXXX() ...
-
spring boot / cloud (三) 集成springfox-swagger2构建在线API文档
spring boot / cloud (三) 集成springfox-swagger2构建在线API文档 前言 不能同步更新API文档会有什么问题? 理想情况下,为所开发的服务编写接口文档,能提高与 ...
-
spring配置datasource三种方式
详见:http://blog.yemou.net/article/query/info/tytfjhfascvhzxcytp34 spring配置datasource三种方式 1.使用org.spri ...
-
Spring IOC(三)依赖注入
本系列目录: Spring IOC(一)概览 Spring IOC(二)容器初始化 Spring IOC(三)依赖注入 Spring IOC(四)总结 目录 1.AbstractBeanFactory ...
-
Spring的第三天AOP之xml版
Spring的第三天AOP之xml版 ssm框架 spring AOP介绍 AOP(Aspect Oriented Programming),面向切面编程.它出来的目的并不是去取代oop,而是对它的 ...
-
Spring Boot 2 (三):Spring Boot 2 相关开源软件
Spring Boot 2 (三):Spring Boot 2 相关开源软件 一.awesome-spring-boot Spring Boot 中文索引,这是一个专门收集 Spring Boot 相 ...
-
Spring Environment(三)生命周期
Spring Environment(三)生命周期 Spring 系列目录(https://www.cnblogs.com/binarylei/p/10198698.html) Spring Envi ...
-
Spring IOC(三)单例 bean 的注册管理
Spring IOC(三)单例 bean 的注册管理 Spring 系列目录(https://www.cnblogs.com/binarylei/p/10198698.html) 在 Spring 中 ...
随机推荐
-
延时调用的php代码
比如我们想做一个类似于康盛uchome的定时触发任务,任务靠用户访问触发的,但是你触发任务是不能影响用户本身对页面的访问速度(也就是说不能任务执行十秒钟你就让用户等待十秒钟)刚好昨天把这个弄完了.拿出 ...
-
input 正则限制输入内容
js 限制input只能输入数字小数点也不能输入或者是只能输入数字,能输小数点等等,本文大致整理了一些,感兴趣的朋友可以收藏下 代码如下: 1 <input type="text& ...
-
深入理解PHP内核(十)变量及数据类型-类型提示的实现
原文链接:http://www.orlion.ga/253/ PHP是弱类型语言,向方法传递参数时也并不严格检查数据类型.不过有时候需要判断传递到方法中的参数,为此PHP中提供了一些函数来判断数据的类 ...
-
github/gitlab 管理多个ssh key
github/gitlab 管理多个ssh key 以前只使用一个 ssh key 在github上提交代码,由于工作原因,需要再添加一个ssh key在公司的 gitlab上提交代码,下面记录下配置 ...
-
ProgressCircular
https://github.com/eltld/ProgressCircular
-
Android 隐藏RadoiButton左边按钮
声明方式 添加属性 android:button=“@null”? 代码方式 radioBtn.setButtonDrawable(new StateListDrawable());
-
IOS设计模式学习(11)中介者
1 前言 面向对象的设计鼓励把行为分散到不同对象中.这种分散可能导致对象之间的相互关联.在最糟糕的情况下,所有对象都彼此了解并相互操作.但是增加的相互关联又减少了获得的益处.增加的关联似的对象很难或不 ...
-
c语言五子棋
#include <stdio.h>#include <stdlib.h>#include <windows.h>#include <conio.h> ...
-
Windows Zip/CentOS/Radhat系统安装Mysql5.7.x方法
CentOS/Redhat 安装: wget http://dev.mysql.com/get/mysql57-community-release-el7-9.noarch.rpm rpm -Uvh ...
-
串行FLASH文件系统FatFs---转自野火论坛
为了支持长文件名,需要用到FATFS源码中的cc936.c的两个函数ff_convert,ff_wtoupper:这里面直接用了两个大数组(127KB)来做unicode转gbk(OEM)的对照表,这 ...