解析Spring第四天(Spring中的事物、Spring框架来管理模板类)
- JDBC模板技术:
Spring框架中提供了很多持久层的模板类来简化编程,使用模板类编写程序会变的简单
- template 模板
- 都是Spring框架提供XxxTemplate
提供了JDBC模板,Spring框架提供的
- JdbcTemplate类,Connection 表示连接,管理事务 Statement ResultSet
- 如何使用JDBC模板类?
- 在数据库中新增表结构和数据
DROP TABLE IF EXISTS `account`;
CREATE TABLE `account` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(40) DEFAULT NULL,
`money` double DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8; -- ----------------------------
-- Records of account
-- ----------------------------
INSERT INTO `account` VALUES ('1', 'aaa', '1000');
INSERT INTO `account` VALUES ('2', 'bbb', '1000');
INSERT INTO `account` VALUES ('3', 'ccc', '1000');
INSERT INTO `account` VALUES ('4', '熊大', '700');
INSERT INTO `account` VALUES ('5', '熊二', '1200');
INSERT INTO `account` VALUES ('6', '熊三', '800'); - 创建一个普通的Maven工程,引入坐标
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>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.12</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.2.RELEASE</version>
</dependency> <dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.13</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
</dependencies>
- 使用Spring框架来管理模板类,Spring管理内置的连接池
<?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"
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.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--配置连接池-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql:///spring_db" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<!--配置jdbc模板-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
</beans> - 测试jdbcTemplate
package cn.tx.test;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(value = "classpath:applicationContext_jdbc.xml")
public class Demo1_1 {
@Autowired
private JdbcTemplate jdbcTemplate;
/**
* 测试的方式
*/
@Test
public void run1(){
jdbcTemplate.update("insert into account values (null,?,?)","熊二",500);
}
} Spring框架管理开源的连接池
- 配置开源的连接池,使用Druid的连接池,引入坐标
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency> - 新建 一个属性文件后缀为.properties。配置连接数据库的基本信息
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///spring_db
jdbc.username=root
jdbc.password=root - 在xml的文件中配置读取属性文件,连接数据库和配置jdbc模板
<?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"
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.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--配置连接池,使用的是Spring框架内置的连接池
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql:///spring_db" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
-->
<!--使用开源连接池
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql:///spring_db" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
-->
<!--加载属性文件
<bean id="placeholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:jdbc.properties" />
</bean>
-->
<!--第二种写法:使用提供标签的方式-->
<context:property-placeholder location="classpath:jdbc.properties" />
<!--加载属性的文件-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<!--配置jdbc模板-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
</beans> - 对数据的基本操作做测试,增删改查
package cn.tx.test;
import cn.tx.demo1.Account;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(value = "classpath:applicationContext_jdbc.xml")
public class Demo1_1 {
@Autowired
private JdbcTemplate jdbcTemplate;
/**
* 测试的方式
*/
@Test
public void run1(){
jdbcTemplate.update("insert into account values (null,?,?)","熊四",800);
}
/**
* 修改
*/
@Test
public void run2(){
jdbcTemplate.update("update account set name = ?,money = ? where id = ?","光头强",100,7);
}
/**
* 删除
*/
@Test
public void run3(){
jdbcTemplate.update("delete from account where id = ?",7);
}
/**
* 通过id查询
*/
@Test
public void run4(){
Account account = jdbcTemplate.queryForObject("select * from account where id = ?", new BeanMapper(), 6);
System.out.println(account);
}
/**
* 查询所有的数据
*/
@Test
public void run5(){
List<Account> list = jdbcTemplate.query("select * from account", new BeanMapper());
for (Account account : list) {
System.out.println(account);
}
}
}
/**
* 实现类,用来进行数据封装的
*/
class BeanMapper implements RowMapper<Account>{
/**
* 是一行一行进行数据封装的
* @param resultSet
* @param i
* @return
* @throws SQLException
*/
@Override
public Account mapRow(ResultSet resultSet, int i) throws SQLException {
Account account = new Account();
account.setId(resultSet.getInt("id"));
account.setName(resultSet.getString("name"));
account.setMoney(resultSet.getDouble("money"));
return account;
}
}模拟转账
- 编写service层代码
package cn.tx.demo2;
public interface AccountService {
/**
* 转账的方法
* @param out 付款人
* @param in 收款人
* @param money 金额
*/
public void pay(String out,String in,double money);
} - 实现接口
package cn.tx.demo2;
public class AccountServiceImpl implements AccountService {
private AccountDao accountDao;
public void setAccountDao(AccountDao accountDao) {
this.accountDao = accountDao;
}
/**
* 转账方法
* @param out 付款人
* @param in 收款人
* @param money 金额
*/
@Override
public void pay(String out, String in, double money) {
// 调用dao方法
accountDao.outMoney(out,money);
accountDao.inMoney(in,money);
}
} - dao层的代码
package cn.tx.demo2;
public interface AccountDao {
/**
* 付款
* @param out
* @param money
*/
public void outMoney(String out,double money);
/**
* 收款
* @param in
* @param money
*/
public void inMoney(String in,double money);
}
- 实现dao层的接口
package cn.tx.demo2;
import org.springframework.jdbc.core.JdbcTemplate;
public class AccountDaoImpl implements AccountDao {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
/**
* 付款
* @param out
* @param money
*/
@Override
public void outMoney(String out, double money) {
jdbcTemplate.update("update account set money = money - ? where name = ?",money,out);
}
/**
* 收款
* @param in
* @param money
*/
@Override
public void inMoney(String in, double money) {
jdbcTemplate.update("update account set money = money + ? where name = ?",money,in);
}
} - 编写配置文件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"
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.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--第二种写法:使用提供标签的方式-->
<context:property-placeholder location="classpath:jdbc.properties" />
<!--加载属性的文件-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<!--配置Jdbc模板类-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
<!--配置service-->
<bean id="accountService" class="cn.tx.demo2.AccountServiceImpl">
<property name="accountDao" ref="accountDao"/>
</bean>
<!--配置service-->
<bean id="accountDao" class="cn.tx.demo2.AccountDaoImpl">
<property name="jdbcTemplate" ref="jdbcTemplate" />
</bean>
</beans> - 测试转账和收款
package cn.tx.test;
import cn.tx.demo2.AccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(value = "classpath:applicationContext_dao1.xml")
public class Demo2 {
@Autowired
private AccountService accountService;
/**
* 测试转账的方法
*/
@Test
public void testPay(){
accountService.pay("熊大","熊二",100);
}
}在dao层使用JdbcDaoSupport 第二种方式,进行转账和收款的测试
- 同样在service层实现接口
package cn.tx.demo3;
public class AccountServiceImpl implements AccountService {
private AccountDao accountDao;
public void setAccountDao(AccountDao accountDao) {
this.accountDao = accountDao;
}
/**
* 转账方法
* @param out 付款人
* @param in 收款人
* @param money 金额
*/
@Override
public void pay(String out, String in, double money) {
// 调用dao方法
accountDao.outMoney(out,money);
accountDao.inMoney(in,money);
}
} - 注意在dao层编写,继承JdbcDaoSupport 和实现接口AccountDao
package cn.tx.demo3;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao {
/**
* 付款
* @param out
* @param money
*/
@Override
public void outMoney(String out, double money) {
this.getJdbcTemplate().update("update account set money = money - ? where name = ?",money,out);
}
/**
* 收款
* @param in
* @param money
*/
@Override
public void inMoney(String in, double money) {
this.getJdbcTemplate().update("update account set money = money + ? where name = ?",money,in);
}
}
- 编写配置文件
<?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"
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.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--第二种写法:使用提供标签的方式-->
<context:property-placeholder location="classpath:jdbc.properties" />
<!--加载属性的文件-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<!--配置Jdbc模板类
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
-->
<!--配置service-->
<bean id="accountService" class="cn.tx.demo3.AccountServiceImpl">
<property name="accountDao" ref="accountDao"/>
</bean>
<!--配置dao
<bean id="accountDao" class="cn.tx.demo3.AccountDaoImpl">
<property name="jdbcTemplate" ref="jdbcTemplate" />
</bean>
-->
<bean id="accountDao" class="cn.tx.demo3.AccountDaoImpl">
<property name="dataSource" ref="dataSource" />
</bean>
</beans> - 测试使用JdbcDaoSupport 的方法进行转账和收款的测试
package cn.tx.test;
import cn.tx.demo3.AccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(value = "classpath:applicationContext_dao2.xml")
public class Demo3 {
@Autowired
private AccountService accountService;
/**
* 测试转账的方法
*/
@Test
public void testPay(){
accountService.pay("熊大","熊二",100);
}
}
解析Spring第四天(Spring中的事物、Spring框架来管理模板类)的更多相关文章
- 使用Spring框架来管理模板类
1. 刚才编写的代码使用的是new的方式,应该把这些类交给Spring框架来管理. 2. 修改的步骤如下 applicationContext.xml中<beans>标签的开头配置为: * ...
- Spring框架的JDBC模板技术和事物
Spring框架的JDBC模板技术 技术分析之Spring框架的JDBC模板技术概述 1. Spring框架中提供了很多持久层的模板类来简化编程,使用模板类编写程序会变的简单 ...
- Spring中的JDBC模板类入门
1.Spring框架中提供了很多持久层的模板类来简化编程,使用模板类编写程序会变的简单 2.提供了JDBC模板,Spring框架提供的 *JdbcTemplate类 3.Spring框架可以整合Hib ...
- Spring框架的JDBC模板技术概述
1. Spring框架中提供了很多持久层的模板类来简化编程,使用模板类编写程序会变的简单 2. 提供了JDBC模板,Spring框架提供的 * JdbcTemplate类 3. Spring框架可以整 ...
- 演示Spring框架的JDBC模板的简单操作
1. 步骤一:创建数据库的表结构 create database spring_day03; use spring_day03; create table t_account( id int prim ...
- python框架Django中MTV框架之Template(模板/界面)
MTV框架之Template(模板/界面) 关注公众号"轻松学编程"了解更多. 1.模板目录位置 应用下 不需要注册 无法跨应用地进行复用 工程下 需要注册 settings.py ...
- spring学习四:Spring中的后置处理器BeanPostProcessor
BeanPostProcessor接口作用: 如果我们想在Spring容器中完成bean实例化.配置以及其他初始化方法前后要添加一些自己逻辑处理.我们需要定义一个或多个BeanPostProcesso ...
- 【Spring】关于Boot应用中集成Spring Security你必须了解的那些事
Spring Security Spring Security是Spring社区的一个顶级项目,也是Spring Boot官方推荐使用的Security框架.除了常规的Authentication和A ...
- Spring AOP四种实现方式Demo详解与相关知识探究
一.前言 在网络上看到一篇博客Spring实现AOP的4种方式,博主写的很通俗易懂,但排版实在抓狂,对于我这么一个对排版.代码格式有强迫症的人来说,实在是不能忍受~~~~(>_<)~~~~ ...
随机推荐
- 第一章 笔记本电脑安装Linux系统(Centos7)
目标:通过[Linux+Docke+Nginx+Jenkins+k8s(Kubernetes)+CICD(自动化)]进行项目部署 内容:根据个人进度实时分章节记录自己所遇到的问题 一.准备工作 1.下 ...
- Codeforces 1111E DP + 树状数组 + LCA + dfs序
题意:给你一颗树,有q次询问,每次询问给你若干个点,这些点可以最多分出m组,每组要满足两个条件:1:每组至少一个点,2:组内的点不能是组内其它点的祖先,问这样的分组能有多少个? 思路:https:// ...
- Metrics介绍和Spring的集成(转)
转自:http://blog.csdn.net/smallnest/article/details/38491507 http://colobu.com/2014/08/08/Metrics-and- ...
- day10 python算法 冒泡算法 二分法 最快查找算法 c3算法
day10 python 1.冒泡算法 冒泡排序,把列表竖起来看,就像一个个气泡往上去(时间复杂度大) lst = [12,3,3,2424,14,3567,534,324 ...
- echarts.min.js的引入
(1)使用地址引入 <script src="https://cdn.bootcss.com/echarts/3.7.1/echarts.min.js"></sc ...
- Centos7命令行安装Tomcat以及配置防火墙开放端口
[转载]Centos 7 yum安装tomcat 命令: 系统环境CentOS Linux release 7.2.1511 (Core) 一.搭建准备:1.先到tomcat官网https://tom ...
- python 对列表中任意两个数进行操作 (python operate any two elements in list)
python中, 实现列表中的整型元素两两相乘或列表中的数组元素两两相与 1. 假设列表中的元素是整型, 可调用以下函数: def list_any_two_mul(mylist): num ...
- Flume速览
Flume是一个分布式的.可靠的.高可用的海量日志采集.聚合和传输的系统.Java实现,插件丰富,模块分明. 数据流模型:Source-Channel-Sink 事务机制保证了消息传递的可靠性 一.基 ...
- php操作redis--有序集合(sorted set)篇
常用函数:zAdd,zRange,zRem,zCard等. 应用场景:类似集合,可以提供一个优先级的参数来为成员排序,如:分数 连接 $redis = new Redis(); $redis-> ...
- Comet Contest#11 F arewell(DAG计数+FWT子集卷积)
传送门. 题解: 4月YY集训时做过DAG计数,和这个基本上是一样的,但是当时好像直接暴力子集卷积,不然我省选时不至于不会,这个就多了个边不选的概率和子集卷积. DAG计数是个套路来的,利用的是DAG ...