专栏首页闻道于事Spring框架(三) JDBCTemplate,声明式事务,自动装载(注解)

Spring框架(三) JDBCTemplate,声明式事务,自动装载(注解)

 JDBCTemplate

按照标准正常项目的结构

结构图:

model层

dao层 实现  dao:(DateBase Access Object) 数据访问对象,dao层只用来访问数据库和模型层

service层 实现 处理业务逻辑

util层

controller层 控制层

这样的包结构就是一个完整的MVC框架结构

controller层跟页面交互,接受请求,调用哪个方法,传给service层,service层在从dao层调用数据库模板,dao层调用数据库和model层,查询数据库

先在dao层声明方法,在实现方法

在service层声明方法,在实现方法

spring配置

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xmlns:p="http://www.springframework.org/schema/p"
 5     xmlns:context="http://www.springframework.org/schema/context"
 6     xmlns:tx="http://www.springframework.org/schema/tx"
 7     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
 8         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
 9         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
10     
11     <!-- 配置数据源 -->
12     <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
13         <property name="username" value="${jdbc.username}"></property>
14         <property name="password" value="${jdbc.password}"></property>
15         <property name="url" value="${jdbc.url}"></property>
16         <property name="driverClassName" value="${jdbc.driver}"></property>
17     </bean>
18     
19     <!-- 引入  数据库  属性文件 -->
20     <context:property-placeholder location="classpath:db.properties"/>
21     
22     <bean id="userService" class="com.maya.service.impl.UserServiceImpl">
23         <property name="userDao" ref="userDao"></property>
24     </bean>
25     <!-- 这种注入方式需要有get/set方法 -->
26     <bean id="userDao" class="com.maya.dao.impl.UserDaoImpl">
27         <property name="jdbcTemplate" ref="jdbcTemplate"></property>
28     </bean>
29     
30     <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
31         <!-- dateSource数据源 -->
32         <property name="dataSource" ref="dataSource"></property>
33     </bean>
34     
35     <!-- 声明Spring提供的事务管理器 -->
36     <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 
37     <!-- 引入数据源 -->
38         <property name="dataSource" ref="dataSource"></property>
39     </bean>
40     <!-- 事务注解驱动 --> 
41     <tx:annotation-driven transaction-manager="transactionManager"/>
42 
43 </beans>

model:

 1 package com.maya.model;
 2 
 3 public class User {
 4     private Integer id;
 5     private String uname;
 6     private String upassword;
 7     public User() {
 8         super();
 9         // TODO Auto-generated constructor stub
10     }
11     public User(Integer id, String uname, String upassword) {
12         super();
13         this.id = id;
14         this.uname = uname;
15         this.upassword = upassword;
16     }
17     public Integer getId() {
18         return id;
19     }
20     public void setId(Integer id) {
21         this.id = id;
22     }
23     public String getUname() {
24         return uname;
25     }
26     public void setUname(String uname) {
27         this.uname = uname;
28     }
29     public String getUpassword() {
30         return upassword;
31     }
32     public void setUpassword(String upassword) {
33         this.upassword = upassword;
34     }
35     @Override
36     public String toString() {
37         return "User [id=" + id + ", uname=" + uname + ", upassword=" + upassword + "]";
38     }
39     
40     
41 }

dao层 接口:

 1 package com.maya.dao;
 2 
 3 import java.util.List;
 4 
 5 import com.maya.model.User;
 6 
 7 public interface UserDao {
 8 
 9     public List<User> selectAllUser();
10     public int insertUser(User u);
11     public int updateUser(User u);
12     public int deleteUser(int id);
13     //持久化查询,
14     public List<User> selectAllUserRowMapper();
15 
16 }

dao层实现:

 1 package com.maya.dao.impl;
 2 
 3 import java.util.ArrayList;
 4 import java.util.List;
 5 
 6 import org.springframework.jdbc.core.BeanPropertyRowMapper;
 7 import org.springframework.jdbc.core.JdbcTemplate;
 8 import org.springframework.jdbc.support.rowset.SqlRowSet;
 9 import org.springframework.transaction.annotation.Transactional;
10 
11 import com.maya.dao.UserDao;
12 import com.maya.model.User;
13 
14 public class UserDaoImpl implements UserDao {
15     
16     private JdbcTemplate jdbcTemplate;
17 
18     @Override
19     public List<User> selectAllUser() {
20         String sql="select * from p_user";
21         SqlRowSet srs=jdbcTemplate.queryForRowSet(sql);
22         List<User> ulist=new ArrayList<User>();
23         while(srs.next()){
24             User u=new User();
25             u.setId(srs.getInt(1));
26             u.setUname(srs.getString(2));
27             u.setUpassword(srs.getString(3));
28             ulist.add(u);
29         }
30         return ulist;
31     }
32 
33     public JdbcTemplate getJdbcTemplate() {
34         return jdbcTemplate;
35     }
36 
37     public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
38         this.jdbcTemplate = jdbcTemplate;
39     }
40     
41     //手动抛出异常的方法
42     public void runTime(){
43         throw new RuntimeException("异常!!!");
44     }
45     @Override
46     @Transactional
47     public int insertUser(User u) {
48         String sql="insert into p_user values(test1.nextval,?,?)";
49         int i=jdbcTemplate.update(sql, u.getUname(),u.getUpassword());
50         System.out.println("UserDao的返回值:"+i);
51         //runTime();
52         return i;
53     }
54 
55     @Override
56     public int updateUser(User u) {
57         String sql="update p_user p set p.uname=? ,p.upassword=? where p.id=? ";
58         int i=jdbcTemplate.update(sql, u.getUname(),u.getUpassword(),u.getId());
59         return 1;
60     }
61 
62     @Override
63     public int deleteUser(int id) {
64         String sql="delete p_user p where p.id=?";
65         int i=jdbcTemplate.update(sql,id);
66         return 1;
67     }
68 
69     @Override
70     public List<User> selectAllUserRowMapper() {
71         String sql="select * from p_user";
72         List<User> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<User>(User.class));
73         
74         return list;
75     }
76 
77 }

service层 接口:

 1 package com.maya.service;
 2 
 3 import java.util.List;
 4 
 5 import com.maya.model.User;
 6 
 7 public interface UserService {
 8 
 9     public List<User> selectAllUser();
10     public int insertUser(User u);
11     public int updateUser(User u);
12     public int deleteUser(int id);
13     //持久化查询,
14     public List<User> selectAllUserRowMapper();
15 }

service层 实现:

 1 package com.maya.service.impl;
 2 
 3 import java.util.List;
 4 
 5 import com.maya.dao.UserDao;
 6 import com.maya.model.User;
 7 import com.maya.service.UserService;
 8 
 9 public class UserServiceImpl implements UserService{
10     
11     private UserDao userDao;
12 
13     public UserDao getUserDao() {
14         return userDao;
15     }
16 
17     public void setUserDao(UserDao userDao) {
18         this.userDao = userDao;
19     }
20 
21     @Override
22     public List<User> selectAllUser() {
23         List<User> list=userDao.selectAllUser();
24         return list;
25     }
26 
27     @Override
28     public int insertUser(User u) {
29         //直接返回结果
30         return userDao.insertUser(u);
31     }
32 
33     @Override
34     public int updateUser(User u) {
35         int i=userDao.updateUser(u);
36         return i;
37     }
38 
39     @Override
40     public int deleteUser(int id) {
41         int i=userDao.deleteUser(id);
42         return i;
43     }
44 
45     @Override
46     public List<User> selectAllUserRowMapper() {
47         List<User> list=userDao.selectAllUserRowMapper();
48         return list;
49     }
50 
51 }

测试:

 1 package com.maya.controller;
 2 
 3 import static org.junit.Assert.*;
 4 
 5 import java.util.List;
 6 
 7 import org.junit.After;
 8 import org.junit.Before;
 9 import org.junit.Test;
10 import org.springframework.context.support.ClassPathXmlApplicationContext;
11 
12 import com.maya.model.User;
13 import com.maya.service.UserService;
14 
15 public class JuintTest {
16     
17     private ClassPathXmlApplicationContext cac;
18     private UserService userservice;
19 
20     @Before
21     public void setUp() throws Exception {
22         //加载spring-all.xml配置文件
23         cac=new ClassPathXmlApplicationContext("spring-all.xml");
24         userservice=(UserService)cac.getBean("userService");
25     }
26 
27     @After
28     public void tearDown() throws Exception {
29         cac.close();
30     }
31 
32     @Test
33     public void test() {
34 //        List<User> ulist=userservice.selectAllUser();
35 //        for(User u:ulist){
36 //            System.out.println(u);
37 //        }
38 
39 //        List<User> ulist=userservice.selectAllUserRowMapper();
40 //        for(User u:ulist){
41 //            System.out.println(u);
42 //        }
43         
44 //        User u1=new User(null,"0927姓名","999");
45 //        int iu1=userservice.insertUser(u1);
46 //        System.out.println(iu1);
47         
48 //        User u2=new User(10,"update","999");
49 //        int iu2=userservice.updateUser(u2);
50 //        System.out.println(iu2);
51         
52         int iu3=userservice.deleteUser(122);
53         System.out.println(iu3);
54     }
55 
56 }

声明式事务

引入数据源 开启事务注解驱动 并引入 

添加注解 

模拟异常

执行方法后抛出异常

回滚

数据米有添加进去

如果去掉注解,数据会添加进去

dao层 实现:

 1     //手动抛出异常的方法
 2     public void runTime(){
 3         throw new RuntimeException("异常!!!");
 4     }
 5     @Override
 6     @Transactional
 7     public int insertUser(User u) {
 8         String sql="insert into p_user values(test1.nextval,?,?)";
 9         int i=jdbcTemplate.update(sql, u.getUname(),u.getUpassword());
10         System.out.println("UserDao的返回值:"+i);
11         runTime();
12         return i;
13     }

自动装配:

不需要get/set方法

在实现类添加注解,Spring启动扫描到注解:

@Repository //或 @Component @Resource 据说差别不大哦

然后添加到Spring容器里

然后向下扫描到@Autowired

不声明的时候默认根据类型进行属性注入

需要设置属性:

//userservice=(UserService)cac.getBean("userService"); userservice=(UserService)cac.getBean(UserService.class);

配置文件:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xmlns:p="http://www.springframework.org/schema/p"
 5     xmlns:context="http://www.springframework.org/schema/context"
 6     xmlns:tx="http://www.springframework.org/schema/tx"
 7     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
 8         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
 9         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
10     
11     <!-- 配置数据源 -->
12     <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
13         <property name="username" value="${jdbc.username}"></property>
14         <property name="password" value="${jdbc.password}"></property>
15         <property name="url" value="${jdbc.url}"></property>
16         <property name="driverClassName" value="${jdbc.driver}"></property>
17     </bean>
18     
19     <!-- 引入  数据库  属性文件 -->
20     <context:property-placeholder location="classpath:db.properties"/>
21     
22     <!-- 配置Spring扫描器
23         spring加载的时候先去扫描包下的内容,会扫描到一些注解
24      -->
25     <context:component-scan base-package="com.maya"></context:component-scan>
26     
27 <!--     <bean id="userService" class="com.maya.service.impl.UserServiceImpl">
28         <property name="userDao" ref="userDao"></property>
29     </bean>
30     这种注入方式需要有get/set方法
31     <bean id="userDao" class="com.maya.dao.impl.UserDaoImpl">
32         <property name="jdbcTemplate" ref="jdbcTemplate"></property>
33     </bean> -->
34     
35     <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
36         <!-- dateSource数据源 -->
37         <property name="dataSource" ref="dataSource"></property>
38     </bean>
39     
40     <!-- 声明Spring提供的事务管理器 -->
41     <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 
42     <!-- 引入数据源 -->
43         <property name="dataSource" ref="dataSource"></property>
44     </bean>
45     <!-- 事务注解驱动 --> 
46     <tx:annotation-driven transaction-manager="transactionManager"/>
47 
48 </beans>

实现类:

 1 package com.maya.dao.impl;
 2 
 3 import java.util.ArrayList;
 4 import java.util.List;
 5 
 6 import org.springframework.beans.factory.annotation.Autowired;
 7 import org.springframework.jdbc.core.BeanPropertyRowMapper;
 8 import org.springframework.jdbc.core.JdbcTemplate;
 9 import org.springframework.jdbc.support.rowset.SqlRowSet;
10 import org.springframework.stereotype.Repository;
11 import org.springframework.transaction.annotation.Transactional;
12 
13 import com.maya.dao.UserDao;
14 import com.maya.model.User;
15 
16 @Repository  //或  @Component @Resource 据说差别不大哦
17 public class UserDaoImpl implements UserDao {
18     
19     @Autowired
20     private JdbcTemplate jdbcTemplate;
21 
22     @Override
23     public List<User> selectAllUser() {
24         String sql="select * from p_user";
25         SqlRowSet srs=jdbcTemplate.queryForRowSet(sql);
26         List<User> ulist=new ArrayList<User>();
27         while(srs.next()){
28             User u=new User();
29             u.setId(srs.getInt(1));
30             u.setUname(srs.getString(2));
31             u.setUpassword(srs.getString(3));
32             ulist.add(u);
33         }
34         return ulist;
35     }
36 
37 //    public JdbcTemplate getJdbcTemplate() {
38 //        return jdbcTemplate;
39 //    }
40 //
41 //    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
42 //        this.jdbcTemplate = jdbcTemplate;
43 //    }
44     
45     //手动抛出异常的方法
46     public void runTime(){
47         throw new RuntimeException("异常!!!");
48     }
49     @Override
50     @Transactional
51     public int insertUser(User u) {
52         String sql="insert into p_user values(test1.nextval,?,?)";
53         int i=jdbcTemplate.update(sql, u.getUname(),u.getUpassword());
54         System.out.println("UserDao的返回值:"+i);
55         runTime();
56         return i;
57     }
58 
59     @Override
60     public int updateUser(User u) {
61         String sql="update p_user p set p.uname=? ,p.upassword=? where p.id=? ";
62         int i=jdbcTemplate.update(sql, u.getUname(),u.getUpassword(),u.getId());
63         return 1;
64     }
65 
66     @Override
67     public int deleteUser(int id) {
68         String sql="delete p_user p where p.id=?";
69         int i=jdbcTemplate.update(sql,id);
70         return 1;
71     }
72 
73     @Override
74     public List<User> selectAllUserRowMapper() {
75         String sql="select * from p_user";
76         List<User> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<User>(User.class));
77         
78         return list;
79     }
80 
81 }
 1 package com.maya.service.impl;
 2 
 3 import java.util.List;
 4 
 5 import org.springframework.beans.factory.annotation.Autowired;
 6 import org.springframework.stereotype.Repository;
 7 
 8 import com.maya.dao.UserDao;
 9 import com.maya.model.User;
10 import com.maya.service.UserService;
11 
12 @Repository  //或  @Component @Resource 据说差别不大哦
13 public class UserServiceImpl implements UserService{
14     
15     @Autowired
16     private UserDao userDao;
17 
18 //    public UserDao getUserDao() {
19 //        return userDao;
20 //    }
21 //
22 //    public void setUserDao(UserDao userDao) {
23 //        this.userDao = userDao;
24 //    }
25 
26     @Override
27     public List<User> selectAllUser() {
28         List<User> list=userDao.selectAllUser();
29         return list;
30     }
31 
32     @Override
33     public int insertUser(User u) {
34         //直接返回结果
35         return userDao.insertUser(u);
36     }
37 
38     @Override
39     public int updateUser(User u) {
40         int i=userDao.updateUser(u);
41         return i;
42     }
43 
44     @Override
45     public int deleteUser(int id) {
46         int i=userDao.deleteUser(id);
47         return i;
48     }
49 
50     @Override
51     public List<User> selectAllUserRowMapper() {
52         List<User> list=userDao.selectAllUserRowMapper();
53         return list;
54     }
55 
56 }

测试:

 1 package com.maya.controller;
 2 
 3 import static org.junit.Assert.*;
 4 
 5 import java.util.List;
 6 
 7 import org.junit.After;
 8 import org.junit.Before;
 9 import org.junit.Test;
10 import org.springframework.context.support.ClassPathXmlApplicationContext;
11 
12 import com.maya.model.User;
13 import com.maya.service.UserService;
14 
15 public class JuintTest {
16     
17     private ClassPathXmlApplicationContext cac;
18     private UserService userservice;
19 
20     @Before
21     public void setUp() throws Exception {
22         //加载spring-all.xml配置文件
23         cac=new ClassPathXmlApplicationContext("spring-all.xml");
24         //userservice=(UserService)cac.getBean("userService");
25         userservice=(UserService)cac.getBean(UserService.class);
26     }
27 
28     @After
29     public void tearDown() throws Exception {
30         cac.close();
31     }
32 
33     @Test
34     public void test() {
35         List<User> ulist=userservice.selectAllUser();
36         for(User u:ulist){
37             System.out.println(u);
38         }
39 
40 //        List<User> ulist=userservice.selectAllUserRowMapper();
41 //        for(User u:ulist){
42 //            System.out.println(u);
43 //        }
44         
45 //        User u1=new User(null,"0927姓名","999");
46 //        int iu1=userservice.insertUser(u1);
47 //        System.out.println(iu1);
48         
49 //        User u2=new User(10,"update","999");
50 //        int iu2=userservice.updateUser(u2);
51 //        System.out.println(iu2);
52         
53 //        int iu3=userservice.deleteUser(122);
54 //        System.out.println(iu3);
55     }
56 
57 }

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • MyBatis框架(二)

    导包, 配置mybatis的总配置文件: mybatis-config.xml, 1 <?xml version="1.0" encoding="UTF-8"...

    二十三年蝉
  • Java之数据类型,变量赋值

    Java中的基础数据类型(四类八种):   1.整数型     byte----使用byte关键字来定义byte型变量,可以一次定义多个变量并对其进行赋值...

    二十三年蝉
  • spring mvc报错,数据库查询无限死循环

    进行查询的陷入了无限死循环,原因是问题类中包含了回答,回答类中包含了问题,进入了无限死循环 解决方法:在回答类中的问题类属性上加注解:@JsonBackRefe...

    二十三年蝉
  • C语言迷惑行为大赏

    由于你的代码前面并没有执行出错设置errno,因此errno会是0,而对应的描述信息就是Success。

    编程珠玑
  • Springboot前后端分离开发

    .1.springboot前后端分离开发之前要配置好很多东西,这周会详细补充博客内容和遇到的问题的解析

    阮键
  • 一步一步学Linq to sql(八):继承与关系

    1.首先定义的是Topic实体基类,然后两个子类的继承,NewTopic--主题帖,Reply--回复帖。 2.Topic类上的特性,下面先来看一下特性类

    aehyok
  • Remove Element

    问题:删除数组中和elem相等的元素,并且返回新数组大小。英语不好。。。读错题了。。 class Solution { public: int remo...

    用户1624346
  • CodeForces - 706B 二分stl

    #include<iostream> #include<cstdio> #include<cstring> #include<string> #include<...

    Kindear
  • PAT1040 Longest Symmetric String (25分) 中心扩展法+动态规划

    Given a string, you are supposed to output the length of the longest symmetric s...

    vivi
  • 【Gym 100685J】Just Another Disney Problem(交互/排序)

    题意是有n个数(n<1000),你通过问1 a b,后台返回你YES代表a<b,NO代表a>b。要你在10000次询问内给出一个符合的排列。n=1000来说,1...

    饶文津

扫码关注云+社区

领取腾讯云代金券