解析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下如何查看系统是多少位的
在Linux命令行下输入 getconf LONG_BIT 命令
- 2018焦作网络赛-E- Jiu Yuan Wants to Eat
题目描述 You ye Jiu yuan is the daughter of the Great GOD Emancipator. And when she becomes an adult, s ...
- 笔记68 Redis数据库
一.Redis简介 REmote DIctionary Server(Redis) 是一个由Salvatore Sanfilippo写的key-value存储系统.Redis是一个开源的使用ANSI ...
- CSIC_716_20191209【并发编程---GIL和协程】
GIL Global Interpreter Lock 全局解释锁 GIL对含IO的任务来说,会出现不能保证数据安全的情况.如下: from threading import Thread fro ...
- java中的final关键字的用法
一. 什么是final关键字? final在Java中是一个保留的关键字,可以声明成员变量.方法.类以及本地变量.一旦你将引用声明作final,你将不能改变这个引用了,编译器会检查代码,如果你试图将变 ...
- Block 使用总结
- (void)testBlockWeakObj1 { UILabel *tl = [[UILabelalloc]init];//本地局部变量 __weak UILabel *weakTL = tl; ...
- 提高ASP.NET首页性能的方法
1.js压缩文件,css压缩文件,引用的越少越好. 2.用 HTTP Module 控制页面的生命周期. 3.自定义生成动态页面的静态内容 . 4.页面用GZIP压缩. 5.OutputCache 编 ...
- fatal error C1076: compiler limit : internal heap limit reached; use /Zm to specify a higher limit
最近想用一下Xtreme ToolkitPro 界面库,安装后用VC6根据向导 产生一个工程,编译时出现如下的错误: fatal error C1076: compiler limit : inter ...
- 1060 Are They Equal (25 分)
1060 Are They Equal (25 分) If a machine can save only 3 significant digits, the float numbers 1230 ...
- UVA 10242 Fourth Point
题意:给你平行四边形两条边的顶点,让你求第四个点. 思路:要找到俩边的公共点,然后向量运算. AC代码: #include<cstdio> #include<cmath> #i ...