JavaWeb:业务层两种事务管理方式

事务管理

DAO层事务管理

dao层一般完成单个数据库操作,使用Connection可以控制单个事务的提交,回滚。

Service层事务管理

service层一般完成一定的业务逻辑,需要使用多个dao的操作组合完成。所以这些操作要么全部完成要么全部不做。也就是一个事务。

事务管理要加在哪里?

答:Service层,控制整个业务逻辑的隔离性。

例子:转账

View、Servlet和Domain代码

View层:

<h1>转账页面</h1>
<form action="${pageContext.request.contextPath }/AccountServlet" method="post">
付款人:<input type="text" name="from"><br>
收款人:<input type="text" name="to"><br>
金额:<input type="text" name="money"><br>
<input type="submit" value="提交">
</form>
</body>

Domain:


	private Integer id;
	private String name;
	private Double 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 Double getMoney() {
		return money;
	}
	public void setMoney(Double money) {
		this.money = money;
	}

}

Jdbc工具类:

	static ComboPooledDataSource dataSource = null;
	static{
		dataSource=new ComboPooledDataSource();
	}
	
	public static Connection getConnection() throws SQLException{
		return dataSource.getConnection();
	}
	
	public static DataSource getDataSource(){
		return dataSource;
	}
	public static void close(Connection con,PreparedStatement ps,ResultSet rs){
		if(rs!=null){
			try {
				rs.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if(ps!=null){
			try {
				ps.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		if(con!=null){
			try {
				con.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	public static void main(String[] args) throws SQLException {
		System.out.println(new JDBCUtils().getConnection());
	}

	public static void startTransaction() {
		startTransaction();
		
	}

Servlet层:调用业务层的服务进行转账


                
  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值