如何处理java(JDBC)中没有任何框架的事务?

时间:2015-06-16 18:08:27

标签: java jdbc service transactions

我是java的新手。我正在使用简单的JSP / Servlet和Service / Dao架构学习JDBC。请考虑下面给出的代码快照。

package com.login.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        HelloService helloService = new HelloService();
        helloService.doMyUnitOfWork();
    }

}

class HelloService {
    public void doMyUnitOfWork() {
        HelloDao helloDao = new HelloDao();
        // I want to execute all below three works in single unit, it means I want to use single transaction for all database operations.
        // Thus any of my below database operation fails I want to rollback all of them, otherwise commit all in database.
        helloDao.doMyWork1();
        helloDao.doMyWork2();
        helloDao.doMyWork3();
    }
}

class HelloDao {
    public void doMyWork1() {
        // this will do database operation 1.
    }

    public void doMyWork2() {
        // this will do database operation 2.
    }

    public void doMyWork3() {
        // this will do database operation 3.
    }
}

正如我在上面的代码snap中提到的,我需要使用简单的JDBC处理服务层的事务。当我尝试谷歌它时,我得到的几乎是Spring和EJB结果,而不是简单的JDBC。

有可能吗?如果是,那怎么样?

提前致谢。

1 个答案:

答案 0 :(得分:0)

是的,这是可能的。像Hibernate这样的框架在内部使用jdbc。

您可以使用

开始交易
connection.setAutoCommit(false);

您可以回滚您的交易:

connection.rollback();

如果您想将数据保存在数据库中,请致电:

connection.commit();

您可以使用以下方式关闭您的交易:

connection.close();

以下是示例:

Connection connection = ...
try{
connection.setAutoCommit(false);


Statement statement1 = null;
try{
    statement1 = connection.createStatement();
    statement1.executeUpdate(
        "update people set name='John' where id=123");
} finally {
    if(statement1 != null) {
        statement1.close();
    }
}


Statement statement2 = null;
try{
    statement2 = connection.createStatement();
    statement2.executeUpdate(
        "update people set name='Gary' where id=456");
} finally {
    if(statement2 != null) {
        statement2.close();
    }
}

connection.commit();


} catch(Exception e) {
connection.rollback();
}finally {
if(connection != null) {
    connection.close();
}
}

如果将被删除,则从http://tutorials.jenkov.com/jdbc/transaction.html复制。