摘要:由于簡單用戶鏈接數據庫微服務通過注解標注該類為持久化操作對象。由于是的子類,所以屬于的子類異常拋出來,都會回滾數據。添加一個使用接收請求添加一個使用接收請求添加微服務啟動類鏈接數據庫通過編寫數據庫訪問而且支持事物處理機制。
SpringCloud(第 042 篇)鏈接Mysql數據庫,通過JdbcTemplate編寫數據庫訪問,而且支持事物處理機制
-
一、大致介紹1、在數據庫操作中,當遇到異常時,我們最關心的是部分回滾還是整體回滾還是不理會,怎么操作怎么來; 2、所以本章節就著重講解了如何運用Transactional注解來處理事物回滾機制; 3、rollbackFor 屬性:拋出的異常是 rollbackFor 異常的子類時都會回滾數據; 4、noRollbackFor 屬性:拋出的異常是 noRollbackFor 異常的子類時不會回滾數據;拋出的異常不是 noRollbackFor 異常的子類時會回滾數據;二、實現步驟 2.1 添加 maven 引用包
2.2 添加應用配置文件(springms-provider-user-mysql-jdbctemplate-transactionalsrcmainresourcesapplication.yml)4.0.0 springms-provider-user-mysql-jdbctemplate-transactional 1.0-SNAPSHOT jar com.springms.cloud springms-spring-cloud 1.0-SNAPSHOT org.springframework.boot spring-boot-starter-data-jpa org.springframework.boot spring-boot-starter-web mysql mysql-connector-java
server: port: 8335 spring: application: name: springms-provider-user-mysql-jdbctemplate-transactional #全部小寫 ##################################################################################################### # mysql 屬性配置 datasource: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://ip:3306/hmilyylimh username: username password: password jpa: hibernate: #ddl-auto: create #ddl-auto:設為create表示每次都重新建表 ddl-auto: update #ddl-auto:設為update表示每次都不會重新建表 show-sql: true ##################################################################################################### ##################################################################################################### # 打印日志 logging: level: root: INFO org.hibernate: INFO org.hibernate.type.descriptor.sql.BasicBinder: TRACE org.hibernate.type.descriptor.sql.BasicExtractor: TRACE com.springms: DEBUG #####################################################################################################2.3 添加實體用戶類User(springms-provider-user-mysql-jdbctemplate-transactional/src/main/java/com/springms/cloud/entity/User.java)
package com.springms.cloud.entity; public class User { private Long id; private String username; private String name; private Integer age; private String balance; public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } public String getUsername() { return this.username; } public void setUsername(String username) { this.username = username; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public Integer getAge() { return this.age; } public void setAge(Integer age) { this.age = age; } public String getBalance() { return this.balance; } public void setBalance(String balance) { this.balance = balance; } @Override public String toString() { return "User{" + "id=" + id + ", username="" + username + """ + ", name="" + name + """ + ", age=" + age + ", balance="" + balance + """ + "}"; } }2.4 添加實體賬戶類Account(springms-provider-user-mysql-jdbctemplate-transactional/src/main/java/com/springms/cloud/entity/Account.java)
package com.springms.cloud.entity; public class Account { private int id ; private String name ; private double money; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getMoney() { return money; } public void setMoney(double money) { this.money = money; } @Override public String toString() { return "Account{" + "id=" + id + ", name="" + name + """ + ", money=" + money + "}"; } }2.5 添加用戶DAO接口(springms-provider-user-mysql-jdbctemplate-transactional/src/main/java/com/springms/cloud/dao/IUserDao.java)
package com.springms.cloud.dao; import com.springms.cloud.entity.User; import java.util.List; /** * 簡單用戶鏈接Mysql數據庫微服務(通過@Repository注解標注該類為持久化操作對象)。 * * @author hmilyylimh * * @version 0.0.1 * * @date 17/10/18 * */ public interface IUserDao { User findUserById(Long id); List2.6 添加賬號DAO接口(springms-provider-user-mysql-jdbctemplate-transactional/src/main/java/com/springms/cloud/dao/IAccountDao.java)findAllUsers(); int insertUser(User user); int addUser(User user); int replaceUser(User user); }
package com.springms.cloud.dao; import com.springms.cloud.entity.Account; import java.util.List; public interface IAccountDao { int add(Account account); int update(Account account); int delete(int id); Account findAccountById(int id); List2.7 添加用戶DAO接口實現類(springms-provider-user-mysql-jdbctemplate-transactional/src/main/java/com/springms/cloud/dao/impl/UserDaoImpl.java)findAccountList(); }
package com.springms.cloud.dao.impl; import com.springms.cloud.dao.IUserDao; import com.springms.cloud.entity.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Repository; import java.util.List; /** * 簡單用戶鏈接Mysql數據庫微服務(通過@Repository注解標注該類為持久化操作對象)。 * * @author hmilyylimh * * @version 0.0.1 * * @date 17/10/18 * */ @Repository public class UserDaoImpl implements IUserDao { /** * 通過@Resource注解引入JdbcTemplate對象。 */ @Autowired private JdbcTemplate jdbcTemplate; @Override public User findUserById(Long id){ // 1. 定義一個sql語句 String querySQL = "select * from user where id = ?"; // 2. 定義一個RowMapper RowMapper2.8 添加賬號DAO接口實現類(springms-provider-user-mysql-jdbctemplate-transactional/src/main/java/com/springms/cloud/dao/impl/AccountDaoImpl.java)rowMapper = new BeanPropertyRowMapper (User.class); // 3. 執行查詢方法 //List list = jdbcTemplate.query("select * from account where id = ?", new Object[]{id}, new BeanPropertyRowMapper(User.class)); User user = jdbcTemplate.queryForObject(querySQL, new Object[]{id}, rowMapper); return user; } @Override public List findAllUsers(){ // 1. 定義一個sql語句 String querySQL = "select * from user"; // 2. 定義一個RowMapper RowMapper rowMapper = new BeanPropertyRowMapper (User.class); // 3. 執行查詢方法 List users = jdbcTemplate.query(querySQL, new Object[]{}, rowMapper); return users; } @Override public int insertUser(User user) { // 1. 定義一個sql語句 String execSQL = "INSERT into user (username, name, age, balance) values (?, ?, ?, ?)"; // 2. 執行查詢方法 int result = jdbcTemplate.update(execSQL, new Object[]{user.getUsername(), user.getName(), user.getAge(), user.getBalance()}); return result; } @Override public int addUser(User user) { // 1. 定義一個sql語句 String execSQL = "INSERT into user (username, name, age, balance) values (?, ?, ?, ?)"; // 2. 執行查詢方法 int result = jdbcTemplate.update(execSQL, new Object[]{user.getUsername(), user.getName(), user.getAge(), user.getBalance()}); return result; } @Override public int replaceUser(User user) { // 1. 定義一個sql語句 String execSQL = "INSERT into user (username, name, age, balance) values (?, ?, ?, ?)"; // 2. 執行查詢方法 int result = jdbcTemplate.update(execSQL, new Object[]{user.getUsername(), user.getName(), user.getAge(), user.getBalance()}); return result; } }
package com.springms.cloud.dao.impl; import com.springms.cloud.dao.IAccountDao; import com.springms.cloud.entity.Account; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import java.util.List; @Repository public class AccountDaoImpl implements IAccountDao { @Autowired private JdbcTemplate jdbcTemplate; @Override public int add(Account account) { return jdbcTemplate.update("insert into account(name, money) values(?, ?)", account.getName(),account.getMoney()); } @Override public int update(Account account) { return jdbcTemplate.update("UPDATE account SET NAME=? ,money=? WHERE id=?", account.getName(),account.getMoney(),account.getId()); } @Override public int delete(int id) { return jdbcTemplate.update("DELETE from TABLE account where id=?",id); } @Override public Account findAccountById(int id) { List2.9 添加用戶Service接口(springms-provider-user-mysql-jdbctemplate-transactional/src/main/java/com/springms/cloud/service/IUserService.java)list = jdbcTemplate.query("select * from account where id = ?", new Object[]{id}, new BeanPropertyRowMapper(Account.class)); if(list!=null && list.size()>0){ Account account = list.get(0); return account; }else{ return null; } } @Override public List findAccountList() { List list = jdbcTemplate.query("select * from account", new Object[]{}, new BeanPropertyRowMapper(Account.class)); if(list!=null && list.size()>0){ return list; }else{ return null; } } }
package com.springms.cloud.service.impl; import com.springms.cloud.dao.IUserDao; import com.springms.cloud.entity.User; import com.springms.cloud.exception.BusinessExtendsException; import com.springms.cloud.exception.RollbackExceptionExtendsRuntimeException; import com.springms.cloud.service.IUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import java.util.List; /** * 簡單用戶鏈接Mysql數據庫微服務(通過@Service注解標注該類為持久化操作對象)。 * * @author hmilyylimh * * @version 0.0.1 * * @date 17/10/18 * */ @Service public class UserServiceImpl implements IUserService{ @Autowired private IUserDao userDao; @Transactional(readOnly = true) @Override public User findUserById(Long id){ return userDao.findUserById(id); } @Transactional(readOnly = true) @Override public List2.10 添加賬號Service接口(springms-provider-user-mysql-jdbctemplate-transactional/src/main/java/com/springms/cloud/service/IAccountService.java)findAllUsers(){ return userDao.findAllUsers(); } /** * 由于 RuntimeExcepackage com.springms.cloud.service; import com.springms.cloud.entity.User; import java.util.List; /** * 簡單用戶鏈接Mysql數據庫微服務(通過@Service注解標注該類為持久化操作對象)。 * * @author hmilyylimh * * @version 0.0.1 * * @date 17/10/18 * */ public interface IUserService { User findUserById(Long id); List findAllUsers(); int insertUser(User user); int addUser(User user); int replaceUser(User user) throws Exception; }
package com.springms.cloud.service; import com.springms.cloud.entity.Account; import java.util.List; public interface IAccountService { int add(Account account); int update(Account account); int delete(int id); Account findAccountById(int id); List2.11 添加電影Service接口(springms-provider-user-mysql-jdbctemplate-transactional/src/main/java/com/springms/cloud/service/IMovieService.java)findAccountList(); }
package com.springms.cloud.service; import com.springms.cloud.entity.Account; import com.springms.cloud.entity.User; /** * 簡單用戶鏈接Mysql數據庫微服務(通過@Service注解標注該類為持久化操作對象)。 * * @author hmilyylimh * * @version 0.0.1 * * @date 17/10/18 * */ public interface IMovieService { int addMovie(User user, Account account); int insertMovie(User user, Account account) throws Exception; }2.12 添加用戶Service接口實現類(springms-provider-user-mysql-jdbctemplate-transactional/src/main/java/com/springms/cloud/service/impl/UserServiceImpl.java)
package com.springms.cloud.service.impl; import com.springms.cloud.dao.IUserDao; import com.springms.cloud.entity.User; import com.springms.cloud.exception.BusinessExtendsException; import com.springms.cloud.exception.RollbackExceptionExtendsRuntimeException; import com.springms.cloud.service.IUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import java.util.List; /** * 簡單用戶鏈接Mysql數據庫微服務(通過@Service注解標注該類為持久化操作對象)。 * * @author hmilyylimh * * @version 0.0.1 * * @date 17/10/18 * */ @Service public class UserServiceImpl implements IUserService{ @Autowired private IUserDao userDao; @Transactional(readOnly = true) @Override public User findUserById(Long id){ return userDao.findUserById(id); } @Transactional(readOnly = true) @Override public List2.12 添加賬號Service接口實現類(springms-provider-user-mysql-jdbctemplate-transactional/src/main/java/com/springms/cloud/service/impl/AccountServiceImpl.java)findAllUsers(){ return userDao.findAllUsers(); } /** * 由于 RuntimeException、RollbackExceptionExtendsRuntimeException 是 Exception 的子類,所以屬于 Exception 的子類異常拋出來,都會回滾數據。 * * @param user * @return */ @Transactional(propagation = Propagation.REQUIRED, isolation= Isolation.DEFAULT, rollbackFor = Exception.class) @Override public int insertUser(User user) { int result = userDao.insertUser(user); if(result > 0){ // throw new RuntimeException("拋出 RuntimeException 異常,測試 rollbackFor = Exception.class 是否有效?"); throw new RollbackExceptionExtendsRuntimeException("拋出 RollbackExceptionExtendsRuntimeException 異常,測試 rollbackFor = Exception.class 是否有效?"); } return result; } @Override public int addUser(User user) { return userDao.addUser(user); } /** * * 由于 RollbackExceptionExtendsException 是 Exception 的子類,不是 BusinessExtendsException 的子類,所以拋出該異常,會回滾數據;
* *注意:如果要使得 noRollbackFor 屬性生效,注解中 @Transactional 必須得只有 noRollbackFor 屬性,然后 noRollbackFor 的異常必須得是自己定義的異常,然后拋 RuntimeException 異常,這樣我們才可以測出 noRollbackFor 回滾與不回滾的場景出來; * * @param user * @return */ @Transactional(noRollbackFor = BusinessExtendsException.class) @Override public int replaceUser(User user) throws Exception { int result = userDao.insertUser(user); if(result > 0){ // throw new NullPointerException("拋出 NullPointerException 異常,測試 noRollbackFor = RuntimeException.class 是否有效?"); // throw new RollbackExceptionExtendsException("拋出 RollbackExceptionExtendsException 異常,測試 noRollbackFor = RuntimeException.class 是否有效?"); // throw new BusinessSubExtendsException("拋出 BusinessSubExtendsException 異常,測試 noRollbackFor = RuntimeException.class 是否有效?"); throw new RuntimeException("拋出 RuntimeException 異常,測試 noRollbackFor = RuntimeException.class 是否有效?"); } return result; } }
package com.springms.cloud.service.impl; import com.springms.cloud.dao.IAccountDao; import com.springms.cloud.entity.Account; import com.springms.cloud.service.IAccountService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class AccountServiceImpl implements IAccountService { @Autowired IAccountDao accountDAO; @Override public int add(Account account) { return accountDAO.add(account); } @Override public int update(Account account) { return accountDAO.update(account); } @Override public int delete(int id) { return accountDAO.delete(id); } @Override public Account findAccountById(int id) { return accountDAO.findAccountById(id); } @Override public List2.13 添加電影Service接口實現類(springms-provider-user-mysql-jdbctemplate-transactional/src/main/java/com/springms/cloud/service/impl/MovieServiceImpl.java)findAccountList() { return accountDAO.findAccountList(); } }
package com.springms.cloud.service.impl; import com.springms.cloud.dao.IAccountDao; import com.springms.cloud.dao.IUserDao; import com.springms.cloud.entity.Account; import com.springms.cloud.entity.User; import com.springms.cloud.exception.BusinessExtendsException; import com.springms.cloud.exception.BusinessSubExtendsException; import com.springms.cloud.service.IMovieService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; /** * 簡單用戶鏈接Mysql數據庫微服務(通過@Service注解標注該類為持久化操作對象)。 * * @author hmilyylimh * * @version 0.0.1 * * @date 17/10/18 * */ @Service public class MovieServiceImpl implements IMovieService { @Autowired private IUserDao userDao; @Autowired private IAccountDao accountDao; @Transactional(propagation = Propagation.REQUIRED, isolation= Isolation.DEFAULT, rollbackFor = Exception.class) @Override public int addMovie(User user, Account account) { int result1 = userDao.addUser(user); int result2 = accountDao.add(account); if(result1 > 0 || result2 > 0){ throw new RuntimeException("拋出 RuntimeException 異常,測試 rollbackFor = Exception.class 是否有效?"); } return 0; } @Transactional(noRollbackFor = BusinessExtendsException.class) @Override public int insertMovie(User user, Account account) throws Exception { int result1 = userDao.insertUser(user); int result2 = accountDao.add(account); if(result1 > 0 || result2 > 0){ // throw new NullPointerException("拋出 NullPointerException 異常,測試 noRollbackFor = RuntimeException.class 是否有效?"); // throw new RollbackExceptionExtendsException("拋出 RollbackExceptionExtendsException 異常,測試 noRollbackFor = RuntimeException.class 是否有效?"); throw new BusinessSubExtendsException("拋出 BusinessSubExtendsException 異常,測試 noRollbackFor = RuntimeException.class 是否有效?"); // throw new RuntimeException("拋出 RuntimeException 異常,測試 noRollbackFor = RuntimeException.class 是否有效?"); } return 0; } }2.14 添加繼承Exception的異常類BusinessExtendsException(springms-provider-user-mysql-jdbctemplate-transactional/src/main/java/com/springms/cloud/exception/BusinessExtendsException.java)
package com.springms.cloud.exception; /** * * * @author hmilyylimh * * @version 0.0.1 * * @date 17/10/18 * */ public class BusinessExtendsException extends Exception { public BusinessExtendsException() { } public BusinessExtendsException(String message) { super(message); } public BusinessExtendsException(String message, Throwable cause) { super(message, cause); } public BusinessExtendsException(Throwable cause) { super(cause); } public BusinessExtendsException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }2.15 添加繼承BusinessExtendsException的異常類(springms-provider-user-mysql-jdbctemplate-transactional/src/main/java/com/springms/cloud/exception/BusinessSubExtendsException.java)
package com.springms.cloud.exception; /** * * * @author hmilyylimh * * @version 0.0.1 * * @date 17/10/18 * */ public class BusinessSubExtendsException extends BusinessExtendsException { public BusinessSubExtendsException() { } public BusinessSubExtendsException(String message) { super(message); } public BusinessSubExtendsException(String message, Throwable cause) { super(message, cause); } public BusinessSubExtendsException(Throwable cause) { super(cause); } public BusinessSubExtendsException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }2.16 添加繼承Exception的異常類RollbackExceptionExtendsException(springms-provider-user-mysql-jdbctemplate-transactional/src/main/java/com/springms/cloud/exception/RollbackExceptionExtendsException.java)
package com.springms.cloud.exception; /** * * * @author hmilyylimh * * @version 0.0.1 * * @date 17/10/18 * */ public class RollbackExceptionExtendsException extends Exception { public RollbackExceptionExtendsException() { } public RollbackExceptionExtendsException(String message) { super(message); } public RollbackExceptionExtendsException(String message, Throwable cause) { super(message, cause); } public RollbackExceptionExtendsException(Throwable cause) { super(cause); } public RollbackExceptionExtendsException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }2.17 添加繼承RuntimeException的異常類(springms-provider-user-mysql-jdbctemplate-transactional/src/main/java/com/springms/cloud/exception/RollbackExceptionExtendsRuntimeException.java)
package com.springms.cloud.exception; /** * 回滾異常,測試語句:@Transactional(propagation = Propagation.REQUIRED, isolation= Isolation.DEFAULT, rollbackFor = Exception.class) 是否生效。 * * 結果:含有該屬性的 rollbackFor = Exception.class,只要拋出的異常屬于 Exception 的子類的話,就可以正常回滾數據; * * @author hmilyylimh * * @version 0.0.1 * * @date 17/10/18 * */ public class RollbackExceptionExtendsRuntimeException extends RuntimeException { public RollbackExceptionExtendsRuntimeException() { } public RollbackExceptionExtendsRuntimeException(String message) { super(message); } public RollbackExceptionExtendsRuntimeException(String message, Throwable cause) { super(message, cause); } public RollbackExceptionExtendsRuntimeException(Throwable cause) { super(cause); } public RollbackExceptionExtendsRuntimeException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }2.18 添加用戶Web訪問層Controller(springms-provider-user-mysql-jdbctemplate-transactional/src/main/java/com/springms/cloud/controller/UserMysqlJdbcTransactionalController.java)
package com.springms.cloud.controller; import com.springms.cloud.service.IUserService; import com.springms.cloud.entity.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.List; /** * 用戶微服務Controller。 * * @author hmilyylimh * * @version 0.0.1 * * @date 17/10/18 * */ @RestController public class UserMysqlJdbcTransactionalController { @Autowired private IUserService userService; @GetMapping("/simplejdbc/{id}") public User findUserById(@PathVariable Long id) { return this.userService.findUserById(id); } @GetMapping("/simplejdbc/list") public List2.19 添加賬號Web訪問層Controller(springms-provider-user-mysql-jdbctemplate-transactional/src/main/java/com/springms/cloud/controller/AccountController.java)findAllUsers() { List users = this.userService.findAllUsers(); List resultUsers = new ArrayList<>(users.subList(users.size()-6, users.size())); return resultUsers; } /** * 添加一個student,使用postMapping接收post請求 * * http://localhost:8315/simple/addUser?username=user11&age=11&balance=11 * * @return */ @PostMapping("/simplejdbc/insertUser") public User insertUser(@RequestParam(value = "username", required=false) String username, @RequestParam(value = "age", required=false) Integer age, @RequestParam(value = "balance", required=false) String balance){ User user=new User(); user.setUsername(username); user.setName(username); user.setAge(age); user.setBalance(balance); int result = userService.insertUser(user); if(result > 0){ return user; } user.setId(0L); user.setName(null); user.setUsername(null); user.setBalance(null); return user; } /** * 添加一個student,使用postMapping接收post請求 * * http://localhost:8315/simple/addUser?username=user11&age=11&balance=11 * * @return */ @PostMapping("/simplejdbc/addUser") public User addUser(@RequestParam(value = "username", required=false) String username, @RequestParam(value = "age", required=false) Integer age, @RequestParam(value = "balance", required=false) String balance){ User user=new User(); user.setUsername(username); user.setName(username); user.setAge(age); user.setBalance(balance); int result = userService.addUser(user); if(result > 0){ return user; } user.setId(0L); user.setName(null); user.setUsername(null); user.setBalance(null); return user; } /** * 添加一個student,使用postMapping接收post請求 * * http://localhost:8315/simple/addUser?username=user11&age=11&balance=11 * * @return */ @PostMapping("/simplejdbc/replaceUser") public User replaceUser(@RequestParam(value = "username", required=false) String username, @RequestParam(value = "age", required=false) Integer age, @RequestParam(value = "balance", required=false) String balance) throws Exception { User user=new User(); user.setUsername(username); user.setName(username); user.setAge(age); user.setBalance(balance); int result = 0; result = userService.replaceUser(user); user.setId((long) 0); user.setName(null); user.setUsername(null); user.setBalance(null); return user; } }
package com.springms.cloud.controller; import com.springms.cloud.entity.Account; import com.springms.cloud.service.IAccountService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("/account") public class AccountController { @Autowired IAccountService accountService; @RequestMapping(value = "/list",method = RequestMethod.GET) public List2.20 添加電影Web訪問層Controller(springms-provider-user-mysql-jdbctemplate-transactional/src/main/java/com/springms/cloud/controller/MovieMysqlJdbcTransactionalController.java)getAccounts(){ return accountService.findAccountList(); } @RequestMapping(value = "/{id}",method = RequestMethod.GET) public Account getAccountById(@PathVariable("id") int id){ return accountService.findAccountById(id); } @RequestMapping(value = "/{id}",method = RequestMethod.PUT) public String updateAccount(@PathVariable("id")int id , @RequestParam(value = "name",required = true)String name, @RequestParam(value = "money" ,required = true)double money){ Account account=new Account(); account.setMoney(money); account.setName(name); account.setId(id); int t=accountService.update(account); if(t==1){ return account.toString(); }else { return "fail"; } } @RequestMapping(value = "",method = RequestMethod.POST) public String postAccount( @RequestParam(value = "name")String name, @RequestParam(value = "money" )double money){ Account account=new Account(); account.setMoney(money); account.setName(name); int t= accountService.add(account); if(t==1){ return account.toString(); }else { return "fail"; } } }
package com.springms.cloud.controller; import com.springms.cloud.entity.Account; import com.springms.cloud.entity.User; import com.springms.cloud.service.IMovieService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; /** * 用戶微服務電影Controller。 * * @author hmilyylimh * * @version 0.0.1 * * @date 17/10/18 * */ @RestController public class MovieMysqlJdbcTransactionalController { @Autowired private IMovieService moiveService; /** * 添加一個student,使用postMapping接收post請求 * * http://localhost:8335/simple/addUser?username=user11&age=11&balance=11 * * @return */ @PostMapping("/movie/addMovie") public User addMovie(@RequestParam(value = "username", required=false) String username, @RequestParam(value = "age", required=false) Integer age, @RequestParam(value = "balance", required=false) String balance){ User user=new User(); user.setUsername(username); user.setName(username); user.setAge(age); user.setBalance(balance); Account account = new Account(); account.setName(username); account.setMoney(Double.parseDouble(balance)); int result = moiveService.addMovie(user, account); if(result > 0){ return user; } user.setId(0L); user.setName(null); user.setUsername(null); user.setBalance(null); return user; } /** * 添加一個student,使用postMapping接收post請求 * * http://localhost:8335/simple/addUser?username=user11&age=11&balance=11 * * @return */ @PostMapping("/movie/insertMovie") public User insertMovie(@RequestParam(value = "username", required=false) String username, @RequestParam(value = "age", required=false) Integer age, @RequestParam(value = "balance", required=false) String balance) throws Exception { User user=new User(); user.setUsername(username); user.setName(username); user.setAge(age); user.setBalance(balance); Account account = new Account(); account.setName(username); account.setMoney(Double.parseDouble(balance)); int result = moiveService.insertMovie(user, account); if(result > 0){ return user; } user.setId(0L); user.setName(null); user.setUsername(null); user.setBalance(null); return user; } }2.21 添加微服務啟動類(springms-provider-user-mysql-jdbctemplate-transactional/src/main/java/com/springms/cloud/MsProviderUserMysqlJdbcTransactionalApplication.java)
package com.springms.cloud; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * 鏈接Mysql數據庫,通過JdbcTemplate編寫數據庫訪問,而且支持事物處理機制。 * * @author hmilyylimh * * @version 0.0.1 * * @date 17/10/18 * */ @SpringBootApplication public class MsProviderUserMysqlJdbcTransactionalApplication { public static void main(String[] args) { SpringApplication.run(MsProviderUserMysqlJdbcTransactionalApplication.class, args); System.out.println("【【【【【【 鏈接MysqlJdbcTransactional數據庫微服務 】】】】】】已啟動."); } }三、測試
/**************************************************************************************** 一、簡單用戶鏈接Mysql數據庫微服務(通過JdbcTemplate編寫數據訪問,而且支持事物處理機制,使用 rollbackFor 屬性,數據回滾): 1、給 insertUser 方法添加注解:@Transactional(propagation = Propagation.REQUIRED, isolation= Isolation.DEFAULT, rollbackFor = Exception.class); 2、insertUser 拋出 RollbackExceptionExtendsRuntimeException 異常; 3、啟動 springms-provider-user-mysql-jdbctemplate-transactional 模塊服務,啟動1個端口; 4、在瀏覽器輸入地址 http://localhost:8315/simplejdbc/list 可以看到所有用戶信息成功的被打印出來; 5、使用 REST Client 執行 "/simplejdbc/insertUser" 添加參數執行接口,結果數據沒有入庫,數據被回滾了; ****************************************************************************************/ /**************************************************************************************** 二、簡單用戶鏈接Mysql數據庫微服務(通過JdbcTemplate編寫數據訪問,而且支持事物處理機制,使用 noRollbackFor 屬性,數據回滾): 1、給 replaceUser 方法添加注解:@Transactional(noRollbackFor = BusinessExtendsException.class); 2、replaceUser 拋出 RuntimeException 異常; 3、啟動 springms-provider-user-mysql-jdbctemplate-transactional 模塊服務,啟動1個端口; 4、在瀏覽器輸入地址 http://localhost:8315/simplejdbc/list 可以看到所有用戶信息成功的被打印出來; 5、使用 REST Client 執行 "/simplejdbc/replaceUser" 添加參數執行接口,結果數據沒有入庫,數據被回滾了; ****************************************************************************************/ /**************************************************************************************** 三、簡單用戶鏈接Mysql數據庫微服務(通過JdbcTemplate編寫數據訪問,而且支持事物處理機制,使用 noRollbackFor 屬性,數據沒有回滾): 1、給 replaceUser 方法添加注解:@Transactional(noRollbackFor = BusinessExtendsException.class); 2、replaceUser 拋出 BusinessSubExtendsException 異常; 3、啟動 springms-provider-user-mysql-jdbctemplate-transactional 模塊服務,啟動1個端口; 4、在瀏覽器輸入地址 http://localhost:8315/simplejdbc/list 可以看到所有用戶信息成功的被打印出來; 5、使用 REST Client 執行 "/simplejdbc/replaceUser" 添加參數執行接口,結果數據已經入庫了,數據沒有回滾了; 注意:如果要使得 noRollbackFor 屬性生效,注解中 @Transactional 必須得只有 noRollbackFor 屬性,然后 noRollbackFor 的異常必須得是自己定義的異常,然后拋 RuntimeException 異常,這樣我們才可以測出 noRollbackFor 回滾與不回滾的場景出來; ****************************************************************************************/ /**************************************************************************************** 四、簡單用戶鏈接Mysql數據庫微服務(通過JdbcTemplate編寫數據訪問,而且支持事物處理機制,同時操作多個DAO文件入庫,然后選擇注解是否進行回滾數據): 這里就不做多的解釋了,MovieServiceImpl 就是操作多個DAO文件入庫,然后處理是否回滾數據的。 注意:如果要使得 noRollbackFor 屬性生效,注解中 @Transactional 必須得只有 noRollbackFor 屬性,然后 noRollbackFor 的異常必須得是自己定義的異常,然后拋 RuntimeException 異常,這樣我們才可以測出 noRollbackFor 回滾與不回滾的場景出來; rollbackFor 屬性:拋出的異常是 rollbackFor 異常的子類時都會回滾數據; noRollbackFor 屬性:拋出的異常是 noRollbackFor 異常的子類時不會回滾數據;拋出的異常不是 noRollbackFor 異常的子類時會回滾數據; ****************************************************************************************/四、下載地址
https://gitee.com/ylimhhmily/SpringCloudTutorial.git
SpringCloudTutorial交流QQ群: 235322432
SpringCloudTutorial交流微信群: 微信溝通群二維碼圖片鏈接
歡迎關注,您的肯定是對我最大的支持!!!
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/67818.html
摘要:通過注解引入對象。添加一個使用接收請求添加賬號訪問層添加微服務啟動類鏈接數據庫通過編寫數據庫訪問。 SpringCloud(第 041 篇)鏈接Mysql數據庫,通過JdbcTemplate編寫數據庫訪問 - 一、大致介紹 1、前面章節提到了JPA操作訪問數據庫,本章節我們講解一下如何用JdbcTemplate操作訪問數據庫; 2、使用JdbcTemplate是一個相對更底層的操作,可...
摘要:添加一個使用接收請求添加用戶微服務啟動類鏈接數據庫通過編寫數據庫訪問。 SpringCloud(第 039 篇)鏈接Mysql數據庫,通過JpaRepository編寫數據庫訪問 - 一、大致介紹 1、本章節開始講解一下訪問數據庫的操作,不過其實這還不算是SpringCloud的范疇,應該說是SpringBoot的操作范疇,這些就先拋開了,我們就還是講解數據庫的操作; 2、JpaRep...
閱讀 4607·2021-09-26 09:55
閱讀 1352·2019-12-27 12:16
閱讀 879·2019-08-30 15:56
閱讀 1895·2019-08-30 14:05
閱讀 983·2019-08-30 13:05
閱讀 1261·2019-08-30 10:59
閱讀 1437·2019-08-26 16:19
閱讀 1880·2019-08-26 13:47