【问题标题】:Best practices for SQL transactions in JavaJava 中 SQL 事务的最佳实践
【发布时间】:2016-11-23 10:31:19
【问题描述】:

对于特定问题,我希望使用数据库事务。 我过去从未这样做过。我的问题是我是否可以为此使用普通的 JDBC,或者 Java 提供了更好的东西(框架..)来实现这个? 有什么设计模式我可以看看吗?

谢谢

【问题讨论】:

  • 30 秒的谷歌搜索会发现这一点:mkyong.com/jdbc/jdbc-transaction-example
  • 您可以寻找 Hibernate 作为 JDBC 的替代品。
  • @Pramod 如果他从连接数据库开始,我强烈建议首先将 JDBC 理解为 Java 和数据库之间的直接层。此外,由于其复杂性和较长的配置文件,Hibernate 对于初学者来说并不是一个很好的 ORM 示例。
  • 谢谢大家,我了解 JDBC 和 SQL 查询,并且知道如何在 SQL 中使用事务。我在这里寻找关于最佳实践的建议。任何设计模式/任何框架?有什么编排吗?
  • Hibernate 不是 JDBC 的替代品。它建立在 JDBC 之上并增加了很多复杂性。所有 Java SQL 解决方案都使用 JDBC。我会推荐 Spring JdbcTemplate,因为它在不增加太多复杂性的情况下删除了很多样板。

标签: java mysql transactions


【解决方案1】:

您可以在互联网上找到答案,但我会为您总结一下。在交易的情况下,您基本上必须遵循几个步骤:

在try块中:

  • 您必须将自动提交设置为 false,
  • 执行 sql 查询和其他操作(PreparedStatement 优于简单的 Statement),
  • 确保您提交。

在 catch 块中:

  • 回滚数据库更改(以防出错)。

在 finally 块中:

  • 检查是否不为空并关闭所有PreparedStatements,
  • 检查是否不为空并关闭数据库连接。

这是一个示例:

try{
    connection = getDatabaseConnection();
    //set connection auto commit to false
    connection.setAutoCommit(false);

    PreparedStatement sqlPreparedStatement = connection.prepareStatement("sql statement here");
    //set all the values in the prepared statement
    sqlPreparedStatement.setString(1,"string");
    sqlPreparedStatement.setString(2,"anotherstring");

    sqlPreparedStatement.executeUpdate();

    PreparedStatement secondSqlStatement = connection.prepareStatement("sql statement here");
    //set all the values in the prepared statement
    secondSqlStatement.setString(1,"whatever");
    secondSqlStatement.setString(2,"sample");

    secondSqlStatement.executeUpdate();

    //commit the changes
    connection.commit();
} catch (SQLException e) {
    e.printStackTrace();//or whatever
    //rollback the changes
    connection.rollback();   
} finally {
    //close the PreparedStatement and the connection if not null
    if (sqlPreparedStatement != null) {
        sqlPreparedStatement.close();
    }
    if (secondSqlStatement != null) {
        secondSqlStatement.close();
    }
    if (connection != null) {
        connection.close();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-25
    • 1970-01-01
    • 1970-01-01
    • 2020-03-22
    • 2016-08-12
    • 2010-09-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多