业务层事务管理
事务管理
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层:调用业务层的服务进行转账