spring提供的事务--纯注解
模拟转账业务 ,出错需要事务回滚,没错正常执行
事务和数据库技术都是spring的内置提供的
1.三层架构
IAccountDao接口
package com.dao; import com.domain.Account; /** * * @date 2019/11/6 15:25 */ public interface IAccountDao { Account findAllById(Integer id); Account findAccountByName(String name); void updateAccount(Account account); }
IAccountDao实现类
package com.dao.impl; import com.dao.IAccountDao; import com.domain.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; /** * 账户实现类 * @date 2019/11/6 15:27 */ @Repository("accountDao") public class IAccountDaoImpl implements IAccountDao { @Autowired private JdbcTemplate template; @Override public Account findAllById(Integer id) { List<Account> query = template.query("select * from account where id= ?", new BeanPropertyRowMapper<>(Account.class), id); return query.isEmpty()?null:query.get(0); } @Override public Account findAccountByName(String name) { List<Account> accounts = template.query("select * from account where name= ?", new BeanPropertyRowMapper<>(Account.class),name); if (accounts.isEmpty()){ return null; } if (accounts.size()>1){ throw new RuntimeException("结果集不唯一"); } return accounts.get(0); } @Override public void updateAccount(Account account) { template.update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId()); } }
domain类
package com.domain; import java.io.Serializable; /** * * @date 2019/11/5 21:32 */ public class Account implements Serializable { private Integer id; private String name; private Float money; @Override public String toString() { return "Account{" + "id=" + id + ", name=‘" + name + ‘\‘‘ + ", money=" + money + ‘}‘; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Float getMoney() { return money; } public void setMoney(Float money) { this.money = money; } }
IAccountService类
package com.service; import com.domain.Account; /** * 账户业务层 * @date 2019/11/7 9:26 */ public interface IAccountService { //根据id查询账户信息 Account findAllById(Integer integer); /*转账 * 转出账户,转入账户,转账金额*/ void transfer(String sourceName, String targetName, Float f); }
service层
测试层
原文地址:https://www.cnblogs.com/july7/p/11812883.html
时间: 2024-10-12 02:21:59