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

JDBCTemplate

按照标准正常项目的结构

结构图:

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

model层

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

service层 实现 处理业务逻辑

util层

controller层 控制层

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

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

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

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

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:p="http://www.springframework.org/schema/p"
     xmlns:context="http://www.springframework.org/schema/context"
     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-4.3.xsd
         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

     <!-- 配置数据源 -->
     <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
         <property name="username" value="${jdbc.username}"></property>
         <property name="password" value="${jdbc.password}"></property>
         <property name="url" value="${jdbc.url}"></property>
         <property name="driverClassName" value="${jdbc.driver}"></property>
     </bean>

     <!-- 引入  数据库  属性文件 -->
     <context:property-placeholder location="classpath:db.properties"/>

     <bean id="userService" class="com.maya.service.impl.UserServiceImpl">
         <property name="userDao" ref="userDao"></property>
     </bean>
     <!-- 这种注入方式需要有get/set方法 -->
     <bean id="userDao" class="com.maya.dao.impl.UserDaoImpl">
         <property name="jdbcTemplate" ref="jdbcTemplate"></property>
     </bean>

     <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
         <!-- dateSource数据源 -->
         <property name="dataSource" ref="dataSource"></property>
     </bean>

     <!-- 声明Spring提供的事务管理器 -->
     <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
     <!-- 引入数据源 -->
         <property name="dataSource" ref="dataSource"></property>
     </bean>
     <!-- 事务注解驱动 -->
     <tx:annotation-driven transaction-manager="transactionManager"/>

 </beans>

model:

 package com.maya.model;

 public class User {
     private Integer id;
     private String uname;
     private String upassword;
     public User() {
         super();
         // TODO Auto-generated constructor stub
     }
     public User(Integer id, String uname, String upassword) {
         super();
         this.id = id;
         this.uname = uname;
         this.upassword = upassword;
     }
     public Integer getId() {
         return id;
     }
     public void setId(Integer id) {
         this.id = id;
     }
     public String getUname() {
         return uname;
     }
     public void setUname(String uname) {
         this.uname = uname;
     }
     public String getUpassword() {
         return upassword;
     }
     public void setUpassword(String upassword) {
         this.upassword = upassword;
     }
     @Override
     public String toString() {
         return "User [id=" + id + ", uname=" + uname + ", upassword=" + upassword + "]";
     }

 }

dao层 接口:

 package com.maya.dao;

 import java.util.List;

 import com.maya.model.User;

 public interface UserDao {

     public List<User> selectAllUser();
     public int insertUser(User u);
     public int updateUser(User u);
     public int deleteUser(int id);
     //持久化查询,
     public List<User> selectAllUserRowMapper();

 }

dao层实现:

 package com.maya.dao.impl;

 import java.util.ArrayList;
 import java.util.List;

 import org.springframework.jdbc.core.BeanPropertyRowMapper;
 import org.springframework.jdbc.core.JdbcTemplate;
 import org.springframework.jdbc.support.rowset.SqlRowSet;
 import org.springframework.transaction.annotation.Transactional;

 import com.maya.dao.UserDao;
 import com.maya.model.User;

 public class UserDaoImpl implements UserDao {

     private JdbcTemplate jdbcTemplate;

     @Override
     public List<User> selectAllUser() {
         String sql="select * from p_user";
         SqlRowSet srs=jdbcTemplate.queryForRowSet(sql);
         List<User> ulist=new ArrayList<User>();
         while(srs.next()){
             User u=new User();
             u.setId(srs.getInt(1));
             u.setUname(srs.getString(2));
             u.setUpassword(srs.getString(3));
             ulist.add(u);
         }
         return ulist;
     }

     public JdbcTemplate getJdbcTemplate() {
         return jdbcTemplate;
     }

     public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
         this.jdbcTemplate = jdbcTemplate;
     }

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

     @Override
     public int updateUser(User u) {
         String sql="update p_user p set p.uname=? ,p.upassword=? where p.id=? ";
         int i=jdbcTemplate.update(sql, u.getUname(),u.getUpassword(),u.getId());
         return 1;
     }

     @Override
     public int deleteUser(int id) {
         String sql="delete p_user p where p.id=?";
         int i=jdbcTemplate.update(sql,id);
         return 1;
     }

     @Override
     public List<User> selectAllUserRowMapper() {
         String sql="select * from p_user";
         List<User> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<User>(User.class));

         return list;
     }

 }

service层 接口:

 package com.maya.service;

 import java.util.List;

 import com.maya.model.User;

 public interface UserService {

     public List<User> selectAllUser();
     public int insertUser(User u);
     public int updateUser(User u);
     public int deleteUser(int id);
     //持久化查询,
     public List<User> selectAllUserRowMapper();
 }

service层 实现:

 package com.maya.service.impl;

 import java.util.List;

 import com.maya.dao.UserDao;
 import com.maya.model.User;
 import com.maya.service.UserService;

 public class UserServiceImpl implements UserService{

     private UserDao userDao;

     public UserDao getUserDao() {
         return userDao;
     }

     public void setUserDao(UserDao userDao) {
         this.userDao = userDao;
     }

     @Override
     public List<User> selectAllUser() {
         List<User> list=userDao.selectAllUser();
         return list;
     }

     @Override
     public int insertUser(User u) {
         //直接返回结果
         return userDao.insertUser(u);
     }

     @Override
     public int updateUser(User u) {
         int i=userDao.updateUser(u);
         return i;
     }

     @Override
     public int deleteUser(int id) {
         int i=userDao.deleteUser(id);
         return i;
     }

     @Override
     public List<User> selectAllUserRowMapper() {
         List<User> list=userDao.selectAllUserRowMapper();
         return list;
     }

 }

测试:

 package com.maya.controller;

 import static org.junit.Assert.*;

 import java.util.List;

 import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
 import org.springframework.context.support.ClassPathXmlApplicationContext;

 import com.maya.model.User;
 import com.maya.service.UserService;

 public class JuintTest {

     private ClassPathXmlApplicationContext cac;
     private UserService userservice;

     @Before
     public void setUp() throws Exception {
         //加载spring-all.xml配置文件
         cac=new ClassPathXmlApplicationContext("spring-all.xml");
         userservice=(UserService)cac.getBean("userService");
     }

     @After
     public void tearDown() throws Exception {
         cac.close();
     }

     @Test
     public void test() {
 //        List<User> ulist=userservice.selectAllUser();
 //        for(User u:ulist){
 //            System.out.println(u);
 //        }

 //        List<User> ulist=userservice.selectAllUserRowMapper();
 //        for(User u:ulist){
 //            System.out.println(u);
 //        }

 //        User u1=new User(null,"0927姓名","999");
 //        int iu1=userservice.insertUser(u1);
 //        System.out.println(iu1);

 //        User u2=new User(10,"update","999");
 //        int iu2=userservice.updateUser(u2);
 //        System.out.println(iu2);

         int iu3=userservice.deleteUser(122);
         System.out.println(iu3);
     }

 }

声明式事务

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

添加注解

模拟异常

执行方法后抛出异常

回滚

数据米有添加进去

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

dao层 实现:

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

自动装配:

不需要get/set方法

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

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

然后添加到Spring容器里

然后向下扫描到@Autowired

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

需要设置属性:

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

配置文件:

 <?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:p="http://www.springframework.org/schema/p"
     xmlns:context="http://www.springframework.org/schema/context"
     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-4.3.xsd
         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

     <!-- 配置数据源 -->
     <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
         <property name="username" value="${jdbc.username}"></property>
         <property name="password" value="${jdbc.password}"></property>
         <property name="url" value="${jdbc.url}"></property>
         <property name="driverClassName" value="${jdbc.driver}"></property>
     </bean>

     <!-- 引入  数据库  属性文件 -->
     <context:property-placeholder location="classpath:db.properties"/>

     <!-- 配置Spring扫描器
         spring加载的时候先去扫描包下的内容,会扫描到一些注解
      -->
     <context:component-scan base-package="com.maya"></context:component-scan>

 <!--     <bean id="userService" class="com.maya.service.impl.UserServiceImpl">
         <property name="userDao" ref="userDao"></property>
     </bean>
     这种注入方式需要有get/set方法
     <bean id="userDao" class="com.maya.dao.impl.UserDaoImpl">
         <property name="jdbcTemplate" ref="jdbcTemplate"></property>
     </bean> -->

     <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
         <!-- dateSource数据源 -->
         <property name="dataSource" ref="dataSource"></property>
     </bean>

     <!-- 声明Spring提供的事务管理器 -->
     <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
     <!-- 引入数据源 -->
         <property name="dataSource" ref="dataSource"></property>
     </bean>
     <!-- 事务注解驱动 -->
     <tx:annotation-driven transaction-manager="transactionManager"/>

 </beans>

实现类:

 package com.maya.dao.impl;

 import java.util.ArrayList;
 import java.util.List;

 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.jdbc.core.BeanPropertyRowMapper;
 import org.springframework.jdbc.core.JdbcTemplate;
 import org.springframework.jdbc.support.rowset.SqlRowSet;
 import org.springframework.stereotype.Repository;
 import org.springframework.transaction.annotation.Transactional;

 import com.maya.dao.UserDao;
 import com.maya.model.User;

 @Repository  //或  @Component @Resource 据说差别不大哦
 public class UserDaoImpl implements UserDao {

     @Autowired
     private JdbcTemplate jdbcTemplate;

     @Override
     public List<User> selectAllUser() {
         String sql="select * from p_user";
         SqlRowSet srs=jdbcTemplate.queryForRowSet(sql);
         List<User> ulist=new ArrayList<User>();
         while(srs.next()){
             User u=new User();
             u.setId(srs.getInt(1));
             u.setUname(srs.getString(2));
             u.setUpassword(srs.getString(3));
             ulist.add(u);
         }
         return ulist;
     }

 //    public JdbcTemplate getJdbcTemplate() {
 //        return jdbcTemplate;
 //    }
 //
 //    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
 //        this.jdbcTemplate = jdbcTemplate;
 //    }

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

     @Override
     public int updateUser(User u) {
         String sql="update p_user p set p.uname=? ,p.upassword=? where p.id=? ";
         int i=jdbcTemplate.update(sql, u.getUname(),u.getUpassword(),u.getId());
         return 1;
     }

     @Override
     public int deleteUser(int id) {
         String sql="delete p_user p where p.id=?";
         int i=jdbcTemplate.update(sql,id);
         return 1;
     }

     @Override
     public List<User> selectAllUserRowMapper() {
         String sql="select * from p_user";
         List<User> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<User>(User.class));

         return list;
     }

 }
 package com.maya.service.impl;

 import java.util.List;

 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Repository;

 import com.maya.dao.UserDao;
 import com.maya.model.User;
 import com.maya.service.UserService;

 @Repository  //或  @Component @Resource 据说差别不大哦
 public class UserServiceImpl implements UserService{

     @Autowired
     private UserDao userDao;

 //    public UserDao getUserDao() {
 //        return userDao;
 //    }
 //
 //    public void setUserDao(UserDao userDao) {
 //        this.userDao = userDao;
 //    }

     @Override
     public List<User> selectAllUser() {
         List<User> list=userDao.selectAllUser();
         return list;
     }

     @Override
     public int insertUser(User u) {
         //直接返回结果
         return userDao.insertUser(u);
     }

     @Override
     public int updateUser(User u) {
         int i=userDao.updateUser(u);
         return i;
     }

     @Override
     public int deleteUser(int id) {
         int i=userDao.deleteUser(id);
         return i;
     }

     @Override
     public List<User> selectAllUserRowMapper() {
         List<User> list=userDao.selectAllUserRowMapper();
         return list;
     }

 }

测试:

 package com.maya.controller;

 import static org.junit.Assert.*;

 import java.util.List;

 import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
 import org.springframework.context.support.ClassPathXmlApplicationContext;

 import com.maya.model.User;
 import com.maya.service.UserService;

 public class JuintTest {

     private ClassPathXmlApplicationContext cac;
     private UserService userservice;

     @Before
     public void setUp() throws Exception {
         //加载spring-all.xml配置文件
         cac=new ClassPathXmlApplicationContext("spring-all.xml");
         //userservice=(UserService)cac.getBean("userService");
         userservice=(UserService)cac.getBean(UserService.class);
     }

     @After
     public void tearDown() throws Exception {
         cac.close();
     }

     @Test
     public void test() {
         List<User> ulist=userservice.selectAllUser();
         for(User u:ulist){
             System.out.println(u);
         }

 //        List<User> ulist=userservice.selectAllUserRowMapper();
 //        for(User u:ulist){
 //            System.out.println(u);
 //        }

 //        User u1=new User(null,"0927姓名","999");
 //        int iu1=userservice.insertUser(u1);
 //        System.out.println(iu1);

 //        User u2=new User(10,"update","999");
 //        int iu2=userservice.updateUser(u2);
 //        System.out.println(iu2);

 //        int iu3=userservice.deleteUser(122);
 //        System.out.println(iu3);
     }

 }
上一篇:Android事件机制之二:onTouch详解


下一篇:P2370 yyy2015c01的U盘(二分+背包)