之前我们讲过spring是一站式框架,我们已经学习了spring框架简单的数据操作。今天我们一起来看看spring针对dao层提供的解决技术jdbcTemplate。我们直接以银行转账为例,完成我们数据库的连接和事务管理。
JdbcTemplate
1、准备工作
准备工作当然还是导包,这里我们又引入了两个新的jar包。
2、操作步骤
(1)配置数据库的相关信息 DriverManagerDataSource dataSource = new DriverManagerDataSource();
(2)创建jdbcTemplate的对象,传输数据库的信息
(3)调用jdbcTemplate对象中的方法实现crud操作
这种方法配置连接数据库是十分麻烦的,接下来我们使用连接池来解决这个问题。
Spring配置连接池
我们将上面test中的设置数据库信息用连接池替换。
我们看到这里的数据库信息也是写死的,我们再来升级一下,将数据库连接信息提取出去db.properties
,在spring配置文件中使用资源文件中数据库信息
配置连接池部分具体使用
最终具体的效果图如下:
Spring的事务管理
1 创建数据库表,添加测试数据
2 在配置文件引入完全约束
<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.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
3 完成service、dao和jdbcTemplate注入关系
4 完成转账操作
(1)service代码
(2)dao代码
5 如果lucy少了1000之后,出现异常,mary不会多1000.丢失了,这时候我们就要用添加事务,
事务解决:
第一步 配置事务管理器
第二步 配置事务注解
第三步 在要使用事务的方法所在类上面添加注解
最终的效果图如下:
dao方法中添加转入转出方法,service中统一方法,在test我们进行测试,两个配置文件。其中applicationContext.xml文件具体如下。
这就是今天的内容。明天,我们开始学习SpringMVC。
个人原创,请多多指教。有帮助到大家的话,关注支持一下哟~
感谢坚持关注的朋友~
世界很大,幸好有你~
欢迎在评论区留下你的问题或困惑,我将每天与你分享我的观点和心得。
聚焦最新科技咨讯,探寻未来智能领域,我是女陶Mario