文章目录
1.实体类
2.持久层接口
3.持久层实现类
4.业务层接口
5.业务层实现类
ConnectionUtils:从数据源中获取一个链接,并且实现和线程的绑定
TransactionManager :和事务管理相关的工具类
AccountDaoImpl实现类
AccountServiceImpl实现类
bean.xml文件
1.实体类
//实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Account {
private Integer id;
private String name;
private Float money;
}
2.持久层接口
//账户的持久层接口
public interface AccountDao {
//查询所有
List<Account> findAllAccount();
//查询一个
Account findAccountById(Integer id);
//保存
void saveAccount(Account account);
//更新
void updateAccount(Account account);
//删除
void deleteAccount(Integer id);
//根据名称查询账户
Account findAccountByName(String accountName);
}
3.持久层实现类
//持久层实现类
@Repository("accountDao")
public class AccountDaoImpl implements AccountDao {
@Autowired
private QueryRunner runner;
public List<Account> findAllAccount() {
try {
return runner.query("select * from account",new BeanListHandler<Account>(Account.class));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public Account findAccountById(Integer id) {
try {
return runner.query("select * from account where id=?",new BeanHandler<Account>(Account.class),id);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void saveAccount(Account account) {
try {
runner.update("insert into account(name,money) values(?,?)",account.getName(),account.getMoney());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void updateAccount(Account account) {
try {
runner.update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void deleteAccount(Integer id) {
try {
runner.update("delete from account where id=?",id);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public Account findAccountByName(String accountName) {
try {
List<Account> accounts = runner.query("select * from account where name=?", new BeanListHandler<Account>(Account.class), accountName);
if (accounts == null || accounts.size() == 0) {
return null;
}
if (accounts.size() > 1) {
throw new RuntimeException("结果集不唯一");
}
return accounts.get(0);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
4.业务层接口
public interface AccountService {
//查询所有
List<Account> findAllAccount();
//查询一个
Account findAccountById(Integer id);
//保存
void saveAccount(Account account);
//更新
void updateAccount(Account account);
//删除
void deleteAccount(Integer id);
//转账
void transfer(String sourceName,String targetName,Float monry);
}
5.业务层实现类
//业务层实现类,业务层调用持久层
@Service("accountService")
public class AccountServiceImpl implements AccountService{
@Autowired
private AccountDao accountDao;
public List<Account> findAllAccount() {
return accountDao.findAllAccount();
}
public Account findAccountById(Integer id) {
return accountDao.findAccountById(id);
}
public void saveAccount(Account account) {
accountDao.saveAccount(account);
}
public void updateAccount(Account account) {
accountDao.updateAccount(account);
}
public void deleteAccount(Integer id) {
accountDao.deleteAccount(id);
}
public void transfer(String sourceName, String targetName, Float money) {
//根据名称查询转出账户
Account source = accountDao.findAccountByName(sourceName);
//根据名称查询转入账户
Account target = accountDao.findAccountByName(targetName);
//转出账户减钱
source.setMoney(source.getMoney()-money);
//转入账户加钱
target.setMoney(target.getMoney()+money);
//更新装出账户
accountDao.updateAccount(source);
//故意制造异常
int i=1/0;
//更新转入账户
accountDao.updateAccount(target);
}
}
对上述代码进行改进:
ConnectionUtils:从数据源中获取一个链接,并且实现和线程的绑定
//从数据源中获取一个链接,并且实现和线程的绑定
public class ConnectionUtils {
private ThreadLocal<Connection> t = new ThreadLocal<Connection>();
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public Connection getConnection(){
try {
//先从线程上获取
Connection conn = t.get();
//判断当前线程上是否有链接
if(conn==null){
//从数据源中获取一个链接,并且存入线程中
conn = dataSource.getConnection();
t.set(conn);
}
return conn;
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
//把连接和线程解绑
public void removeConnection(){
t.remove();
}
}
TransactionManager :和事务管理相关的工具类
//和事务管理相关的工具类
public class TransactionManager {
private ConnectionUtils connectionUtils;
public void setConnectionUtils(ConnectionUtils connectionUtils) {
this.connectionUtils = connectionUtils;
}
public void beginTransaction(){
//开启事务
try {
connectionUtils.getConnection().setAutoCommit(false);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void commit(){
//提交事务
try {
connectionUtils.getConnection().commit();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void rollback(){
//回滚事务
try {
connectionUtils.getConnection().rollback();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void release(){
//释放链接
try {
connectionUtils.getConnection().close();//把conn还回连接池中
connectionUtils.removeConnection();//将conn和线程解绑
} catch (SQLException e) {
e.printStackTrace();
}
}
}
AccountDaoImpl实现类
//持久层实现类
public class AccountDaoImpl implements AccountDao {
private QueryRunner runner;
private ConnectionUtils connectionUtils;
public void setRunner(QueryRunner runner) {
this.runner = runner;
}
public void setConnectionUtils(ConnectionUtils connectionUtils) {
this.connectionUtils = connectionUtils;
}
public List<Account> findAllAccount() {
try {
return runner.query(connectionUtils.getConnection(),"select * from account",new BeanListHandler<Account>(Account.class));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public Account findAccountById(Integer id) {
try {
return runner.query(connectionUtils.getConnection(),"select * from account where id=?",new BeanHandler<Account>(Account.class),id);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void saveAccount(Account account) {
try {
runner.update(connectionUtils.getConnection(),"insert into account(name,money) values(?,?)",account.getName(),account.getMoney());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void updateAccount(Account account) {
try {
runner.update(connectionUtils.getConnection(),"update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void deleteAccount(Integer id) {
try {
runner.update(connectionUtils.getConnection(),"delete from account where id=?",id);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public Account findAccountByName(String accountName) {
try {
List<Account> accounts = runner.query(connectionUtils.getConnection(),"select * from account where name=?", new BeanListHandler<Account>(Account.class), accountName);
if (accounts == null || accounts.size() == 0) {
return null;
}
if (accounts.size() > 1) {
throw new RuntimeException("结果集不唯一");
}
return accounts.get(0);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
AccountServiceImpl实现类
//业务层实现类,业务层调用持久层
public class AccountServiceImpl implements AccountService{
private AccountDao accountDao;
private TransactionManager transactionManager;
public void setAccountDao(AccountDao accountDao) {
this.accountDao = accountDao;
}
public void setTransactionManager(TransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
public List<Account> findAllAccount() {
try {
//1.开启事务
transactionManager.beginTransaction();
//2.执行操作
List<Account> accounts = accountDao.findAllAccount();
//3.提交事务
transactionManager.commit();
//4.返回结果
return accounts;
} catch (Exception e) {
//5.回滚事务
transactionManager.rollback();
//这个必须写,否则产生异常没有返回值,程序编译器就有错
throw new RuntimeException(e);
}finally {
//6.释放资源
transactionManager.release();
}
}
public Account findAccountById(Integer id) {
try {
//1.开启事务
transactionManager.beginTransaction();
//2.执行操作
Account account = accountDao.findAccountById(id);
//3.提交事务
transactionManager.commit();
//4.返回结果
return account;
} catch (Exception e) {
//5.回滚事务
transactionManager.rollback();
throw new RuntimeException(e);
}finally {
//6.释放资源
transactionManager.release();
}
}
public void saveAccount(Account account) {
try {
//1.开启事务
transactionManager.beginTransaction();
//2.执行操作
accountDao.saveAccount(account);
//3.提交事务
transactionManager.commit();
} catch (Exception e) {
//5.回滚事务
transactionManager.rollback();
}finally {
//6.释放资源
transactionManager.release();
}
}
public void updateAccount(Account account) {
try {
//1.开启事务
transactionManager.beginTransaction();
//2.执行操作
accountDao.updateAccount(account );
//3.提交事务
transactionManager.commit();
} catch (Exception e) {
//5.回滚事务
transactionManager.rollback();
}finally {
//6.释放资源
transactionManager.release();
}
}
public void deleteAccount(Integer id) {
try {
//1.开启事务
transactionManager.beginTransaction();
//2.执行操作
accountDao.deleteAccount(id);
//3.提交事务
transactionManager.commit();
} catch (Exception e) {
//5.回滚事务
transactionManager.rollback();
}finally {
//6.释放资源
transactionManager.release();
}
}
public void transfer(String sourceName, String targetName, Float money) {
try {
//1.开启事务
transactionManager.beginTransaction();
//2.执行操作
//根据名称查询转出账户
Account source = accountDao.findAccountByName(sourceName);
//根据名称查询转入账户
Account target = accountDao.findAccountByName(targetName);
//转出账户减钱
source.setMoney(source.getMoney()-money);
//转入账户加钱
target.setMoney(target.getMoney()+money);
//更新装出账户
accountDao.updateAccount(source);
int i=1/0;
//更新转入账户
accountDao.updateAccount(target);
//3.提交事务
transactionManager.commit();
} catch (Exception e) {
//5.回滚事务
transactionManager.rollback();
e.printStackTrace();
}finally {
//6.释放资源
transactionManager.release();
}
}
}
bean.xml文件
<?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:context="http://www.springframework.org/schema/context"
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.xsd">
<!--Spring在创建容器时,要扫描的包-->
<context:component-scan base-package="com.hh"/>
<!--配置AccountDao-->
<bean id="accountDao" class="com.hh.dao.AccountDaoImpl">
<property name="connectionUtils" ref="connectionUtils"/>
<property name="runner" ref="queryRunner"/>
</bean>
<!--配置AccountService-->
<bean id="accountService" class="com.hh.service.AccountServiceImpl">
<property name="transactionManager" ref="transactionManage"/>
<property name="accountDao" ref="accountDao"/>
</bean>
<!--配置事务管理器-->
<bean id="transactionManage" class="com.hh.utils.TransactionManager">
<property name="connectionUtils" ref="connectionUtils"/>
</bean>
<!--配置QueryRunner-->
<bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
</bean>
<!--配置数据源-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!--连接数据库的必备信息-->
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring"/>
<property name="user" value="root"/>
<property name="password" value="123"/>
</bean>
<!--配置ConnectionUtils工具类-->
<bean id="connectionUtils" class="com.hh.utils.ConnectionUtils">
<!--注入数据源-->
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>