本文介绍spring boot,spring jdbc和spring transaction的使用

项目结构

依赖

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>

application

spring.datasource.url=jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&useSSL=false&allowPublicKeyRetrieval=true
spring.datasource.username=root
spring.datasource.password=123
spring.datasource.driver-class-name=com.mysql.jdbc.Driver server.tomcat.uri-encoding=UTF-8
server.port=8888

model层

// 模型层 User.java

package com.springlearn.learn.model;

public class User{
private Integer id;
private String name;
private Integer age;
private String sex; public User(Integer id, String name, Integer age, String sex) {
this.id = id;
this.name = name;
this.age = age;
this.sex = sex;
} public Integer getId() {
return id;
} public String getName() {
return name;
} public Integer getAge() {
return age;
} public String getSex() {
return sex;
} public void setId(Integer id) {
this.id = id;
} public void setName(String name) {
this.name = name;
} public void setAge(Integer age) {
this.age = age;
} public void setSex(String sex) {
this.sex = sex;
} }

mapper层

// UserMapper.java
// 这个层mapper是将数据映射到model层 package com.springlearn.learn.mapper; import java.sql.ResultSet;
import java.sql.SQLException; import com.springlearn.learn.model.User; import org.springframework.jdbc.core.RowMapper; public class UserMapper implements RowMapper<User> {
public static final String sql = "select * from test"; @Override
public User mapRow(ResultSet rs, int rowNum) throws SQLException {
Integer id = rs.getInt("id");
String name = rs.getString("name");
Integer age = rs.getInt("age");
String sex = rs.getString("sex"); return new User(id, name, age, sex);
} }

dao层

// UserDao.java
// dao就是Data Access Object,数据访问对象 // @Transactional(propagation = Propagation.MANDATORY) 声明事务
// MANDATORY只能在其他事物中调用此事务
// REQUIRES_NEW 创建一个新事务并且执行,其他事务挂起
// rollbackFor = UserTransactionException.class 只要抛出了UserTransactionException异常,事务回滚 package com.springlearn.learn.dao; import java.util.List; import javax.sql.DataSource; import com.springlearn.learn.exception.UserTransactionException;
import com.springlearn.learn.mapper.UserMapper;
import com.springlearn.learn.model.User; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional; @Repository
@Transactional
public class UserDao extends JdbcDaoSupport { @Autowired
public UserDao(DataSource dataSource) {
this.setDataSource(dataSource);
} public List<User> getUser() {
String sql = UserMapper.sql; UserMapper userMapper = new UserMapper();
List<User> list = this.getJdbcTemplate().query(sql, userMapper); return list;
} public User getUserById(Integer id) {
String sql = UserMapper.sql+" where id = ?";
Object[] params = new Object[]{id};
UserMapper userMapper = new UserMapper();
User user = this.getJdbcTemplate().queryForObject(sql, params, userMapper);
return user;
} @Transactional(propagation = Propagation.MANDATORY)
public void addAge(Integer id, int addnum) throws UserTransactionException{
User user = this.getUserById(id);
if(user == null) {
throw new UserTransactionException("User not found" + id);
}
int newAge = user.getAge() + addnum;
if(newAge < 0) {
throw new UserTransactionException("The Age in the User" + id + "is illegal" + newAge);
}
user.setAge(newAge); String sql = "update test set age = ? where id = ?;";
this.getJdbcTemplate().update(sql, user.getAge(),user.getId());
} @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = UserTransactionException.class)
public void setAge(int id, int addnum) throws UserTransactionException{
addAge(id, addnum);
}
}

exception层

// UserTransactionException.java
package com.springlearn.learn.exception; public class UserTransactionException extends Exception {
private static final long serialVersionUID = -3128681006635769411L; public UserTransactionException(String message) {
super(message);
}
}

MainController

// MainController.java
package com.springlearn.learn.controller; import java.util.List; import com.springlearn.learn.dao.UserDao;
import com.springlearn.learn.exception.UserTransactionException;
import com.springlearn.learn.model.User; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody; @Controller
public class MainController { @Autowired
private UserDao userdao; @ResponseBody
@RequestMapping(value="/", method=RequestMethod.GET)
public List<User> showAllUser(Model model) {
List<User> list = userdao.getUser(); model.addAttribute("userinfos", list); return list;
} @ResponseBody
@RequestMapping(value = "/setAge", method = RequestMethod.GET)
public String setUserAge(@RequestParam(value="id") int id, @RequestParam(value="addnum") int addnum) {
try{
userdao.setAge(id, addnum);
return "Ok";
}catch (UserTransactionException e){
return e.getMessage();
} }
}

springboot成神之——spring boot,spring jdbc和spring transaction的使用的更多相关文章

  1. Spring Boot 整合JDBC 实现后端项目开发

    一.前言 二.新建Spring Boot 项目 三.Spring Boot 整合JDBC 与MySQL 交互 3.1 新建数据表skr_user 3.2 Jdbcproject 项目结构如下 3.3 ...

  2. Spring Boot系列(三) Spring Boot 之 JDBC

    数据源 类型 javax.sql.DataSource javax.sql.XADataSource org.springframework.jdbc.datasource.embedded,Enbe ...

  3. 【自学Spring Boot】什么是Spring Boot

    为啥要有Spring Boot? 以前大学刚开始学java web的时候,需要搭建起web框架,当时使用的是SSH(struts+spring+hibernate),那就开始搭建吧,初学者哪里知道整套 ...

  4. Spring Boot(十二):spring boot如何测试打包部署

    Spring Boot(十二):spring boot如何测试打包部署 一.开发阶段 1,单元测试 在开发阶段的时候最重要的是单元测试了,springboot对单元测试的支持已经很完善了. (1)在p ...

  5. springboot成神之——ioc容器(依赖注入)

    springboot成神之--ioc容器(依赖注入) spring的ioc功能 文件目录结构 lang Chinese English GreetingService MyRepository MyC ...

  6. Spring Boot 项目学习 (三) Spring Boot + Redis 搭建

    0 引言 本文主要介绍 Spring Boot 中 Redis 的配置和基本使用. 1 配置 Redis 1. 修改pom.xml,添加Redis依赖 <!-- Spring Boot Redi ...

  7. Spring Boot配置篇(基于Spring Boot 2.0系列)

    1:概述 SpringBoot支持外部化配置,配置文件格式如下所示: properties files yaml files environment variables command-line ar ...

  8. 【Spring Boot学习之三】Spring Boot整合数据源

    环境 eclipse 4.7 jdk 1.8 Spring Boot 1.5.2 一.Spring Boot整合Spring JDBC 1.pom.xml <project xmlns=&quo ...

  9. Spring Boot 学习1-创建Spring Boot应用

    如果使用Maven, 确保先安装好Maven再继续. 创建POM文件 在这里有两种方式: 继承Spring Boot parent的pom. 不继承. 继承Spring Boot pom 1 2 3 ...

  10. [转]Spring Boot——2分钟构建spring web mvc REST风格HelloWorld

    Spring Boot——2分钟构建spring web mvc REST风格HelloWorld http://projects.spring.io/spring-boot/ http://spri ...

随机推荐

  1. zabbix原理

    数据采集-->数据存储-->数据展示和分析-->报警 数据采集 SNMP agent ICMP/ssh/IPMT数据存储: cacti:rrd nagios:无数据库.mysql z ...

  2. OpenStack Mitaka HA部署方案(随笔)

    [Toc] https://github.com/wanstack/AutoMitaka # 亲情奉献安装openstack HA脚本 使用python + shell,完成了基本的核心功能(纯二层的 ...

  3. [转载]java调用PageOffice生成word

    一.在开发OA办公或与文档相关的Web系统中,难免会遇到动态生成word文档的需求,为了解决工作中遇到导出word文档的需求,前一段时间上网找了一些资料,在word导出这方面有很多工具可以使用,jac ...

  4. git合并分支与解决冲突

    前提: 当前开发的分支为feature/20161129_317606_algoplatform_1,由于feature/20161130_322574_tmstools_1分支有新内容,所以准备将f ...

  5. 关于this指向问题的总结【转自秘密花园】

    this 的工作原理 JavaScript 有一套完全不同于其它语言的对 this 的处理机制. 在五种不同的情况下 ,this 指向的各不相同. 第一种:全局范围内 this; 当在全部范围内使用  ...

  6. ArcGIS Runtime SDK for WPF之测量距离和面积

    bu不多说,上代码 using System.Windows; using ESRI.ArcGIS.Client; using ESRI.ArcGIS.Client.Tasks; using ESRI ...

  7. 剑指Offer-第一章面试细节总结

    面试细节:行为面试(20%)+技术面试(70%)+应聘者提问(10%) * 行为面试:跳槽者(不要抱怨老板,不要抱怨同事,只为追寻自己的理想而站斗) * 技术面试:1.基础知识点(编程语言,数据结构( ...

  8. UIImage+PYJAnimatedGIF

    UIImage+PYJAnimatedGIF.h: #import <UIKit/UIKit.h> @interface UIImage (PYJAnimatedGIF) + (UIIma ...

  9. yield关键字用法与解析(C# 参考)

    yield 关键字向编译器指示它所在的方法是迭代器块. 编译器生成一个类来实现迭代器块中表示的行为. 在迭代器块中,yield 关键字与 return 关键字结合使用,向枚举器对象提供值. 这是一个返 ...

  10. Windows Communication Foundation (WCF)和Windows CardSpace的示例程序

    微软公司昨天发布了一个Windows Communication Foundation (WCF)和Windows CardSpace的示例程序包,内容极为丰富,从最简单的Hello World到复杂 ...