java - Spring hibernate 事务

标签 java spring hibernate spring-transactions

文档说我们必须在进行一些插入之前开始事务。但是下面的代码是如何运行的呢?因为我在保存后调用 beginTransaction() 。

    @Override
public void insertCustomer(Employees employee) {

    Session session = sessionFactory.openSession();
    session.save(employee);
    session.beginTransaction();
    session.getTransaction().commit();
    session.close();
}

我对 Spring 的 @transactional 属性(称为传播)还有一个疑问,它可以像下面这样配置,

@Transactional(propagation=Propagation.NEVER)

据说这个是非过渡性运行的。这是什么意思?

请帮助我理解上述概念

最佳答案

How the below code runs? Because I am calling the begintransaction after save.

一旦您调用 save(),Hibernate 就不会尝试插入/更新数据库。仅当您尝试提交事务时它才会尝试插入。如果您不提交事务,它将不会按您的预期运行。

@Transactional(propagation=Propagation.NEVER) what does that mean?

以下是 Spring 支持的 7 种不同的事务传播行为

  • PROPAGATION_REQUIRED(默认)
  • PROPAGATION_REQUIRED_NEW
  • PROPAGATION_SUPPORTS
  • PROPAGATION_NOT_SUPPORTED
  • PROPAGATION_MANDATORY
  • PROPAGATION_NEVER
  • PROPAGATION_NESTED

(注意:您不需要在所有方法中都使用事务。您也可以使用没有事务的普通方法)

要在事务下执行方法,请使用@Transactional进行注释。默认情况下,它在 PROPAGATION_REQUIRED 行为下运行,这意味着两件事之一

  1. 如果调用者中没有现有交易,则将激活新交易。
  2. 如果调用方已激活现有事务,则加入现有事务。

当一个方法用@Transaction(prorogation=Propagation.NEVER)注释时,它不应该被另一个方法通过 Activity 事务调用。否则,将会抛出异常。

当您希望在没有 Activity 事务的情况下严格执行特定逻辑/方法时,请使用

Propagation.NEVER。根据我的经验,我从来没有使用过这个属性。 95% 的情况下,您会对默认的 PROPAGATION_REQUIRED 行为感到满意。然而,了解不同的行为是有好处的。

让我用一个例子来解释:

@Component
public class TransactionTutorial {

    @Transactional
    public void aboutRequired() {
        //This method will create a new transaction if it is called with no active transaction 

        //Some logic that should be executed within a transaction

        //normal() method will also run under the newly created transaction.
        normal();

        //An exception will be thrown at this point
        //because aboutNever() is marked as Propagation.NEVER 
        aboutNever();
    }

    @Transactional(propagation=Propagation.NEVER)
    public void aboutNever() {
        //This method should be called without any active transaction.
        //If it is called under active transaction, exception will occur.

        //Some logic that should be executed without a transaction.
    }

    public void normal() {
        //This method is not bothered about surrounding transaction.
        //You can call this method with or without an active transaction.

        //Some logic
    }
}

阅读上面的代码可能会更好地理解。

关于java - Spring hibernate 事务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23888255/

相关文章:

java - 将 protobuf-lite 消息转换为 JSON 并返回

java - 如何在 Java 的构造函数中使用数字创建自定义异常

java - 将列表从 Thymeleaf 传递到 Spring Controller

mysql - 哪种 AWS 产品适用于 Spring MVC 移动应用程序后端?

java - 的用法?在 jsonb 上的 native SQL 查询中

java - 没有静态方法的junit测试

java - 在没有准备语句的 SQL 中转义字符

java - 无法在 thymeleaf 中显示 byte[] 图像

java - Spring Data JPA 规范中三表连接中允许空集

java - RxJava : How to run two sequential calls : second depends on first