解析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种方式,博主写的很通俗易懂,但排版实在抓狂,对于我这么一个对排版.代码格式有强迫症的人来说,实在是不能忍受~~~~(>_<)~~~~ ...
随机推荐
- RK3288 android切换耳麦通道
通过耳机状态切换耳机mic与板子麦/work/rk3288/firefly-rk3288_android5.1_git_20180126/kernel/sound/soc/codecs/es8323. ...
- Mac下homebrew的安装与卸载
mac系统常用的软件安装工具就是homebrew 个人认为通过brew安装比较简单,下面介绍下如何安装 安装和卸载homebrew 安装 /usr/bin/ruby -e "$(curl - ...
- 项目案例之GitLab的数据迁移
项目案例之GitLab的数据迁移 链接:https://pan.baidu.com/s/1CgaEv12cwfbs5RxcNpxdAg 提取码:fytm 复制这段内容后打开百度网盘手机App,操作更方 ...
- Codeforces 1149D 最短路 状压DP
题意及思路:https://blog.csdn.net/yzyyylx/article/details/90145400 这题主要巧妙在分析了最短路算法的性质,得出大小小于等于3的连通块一定不会被再次 ...
- hibernate调用oracle存储过程||函数
pakeage dao.Impl; //调用函数FUN_GET(); public String get(String Id,String Name){ return getSession().cre ...
- redis相关笔记(一.安装及单机及哨兵使用)
redis笔记一 redis笔记二 redis笔记三 1.安装 cd /usr/src #进入下载目录(这个目录自己定) yum install -y wget gcc make tcl #安装依赖 ...
- SQL 删除
SQL Delete 语句(删除表中的记录) DELETE语句用于删除表中现有记录. SQL DELETE 语句 DELETE 语句用于删除表中的行. SQL DELETE 语法 DELETE FRO ...
- 【LeetCode 1】两数之和
描述 [题解] 用个map的话就是O(N)级别的了. [代码] class Solution { public: unordered_map<int,int> mymap; vector& ...
- console.log(([])?true:false); console.log(([]==false?true:false)); console.log(({}==false)?true:false)
下面是题目的类型转换结果: Boolean([]); //true Number([]); //0 Number({}); // NaN Number(false); //0 因此: console. ...
- Hbase表类型的设计
HBase表类型的设计 1.短宽 这种设计一般适用于: * 有大量的列 * 有很少的行 2.高瘦 这种设计一般适用于: * 有很少的列 * 有大量的行 3.短宽-高瘦的对比 短宽 * 使用列名进行查询 ...