简体   繁体   English

“Spring 事务”和“Hibernate 事务”有什么区别

[英]What is the difference between a “Spring transaction” and a “Hibernate transaction”

Could you please explain the difference between the following two types of transactions:您能否解释一下以下两种交易类型之间的区别:

  1. Hibernate transaction休眠事务
  2. Spring transaction春季交易

Also I would like to know about the @Transactional annotation.我也想知道@Transactional注释。

Well for starters they are both Transactions, but they encompass different concepts and components.对于初学者来说,它们都是事务,但它们包含不同的概念和组件。

TL;DR TL; 博士

Hibernate deals with database specific transactions, whereas spring provides a general transaction management service. Hibernate 处理数据库特定的事务,而 spring 提供通用的事务管理服务。 @Transactional is a nice way of configuring transaction management behaviour. @Transactional是配置事务管理行为的好方法。

The long story:长长的故事:

Transactions交易

Transactions are basically units of work (ie changes to something) that are managed as a single operation that can be either committed or rolled back.事务基本上是作为可以提交或回滚的单个操作进行管理的工作单元(即对某事的更改)。 There are lots of different types of transactions in the java world - database, messaging systems like JMS, inter application transactions (for those who are not faint of heart) or anything else that may need to be included in a transaction. Java 世界中有许多不同类型的事务 - 数据库、消息系统(如 JMS)、应用程序间事务(对于那些胆小的人)或任何其他可能需要包含在事务中的事务。 In the Java standard transactions are managed using the Java Transaction API which sets the rules for how to participate in a transaction.在 Java 标准事务中,使用Java Transaction API管理如何参与事务的规则。

Hibernate休眠

Hibernate is an ORM for abstracting database components to Java objects, so its transactions are specifically related to changes made within a database. Hibernate是一个 ORM,用于将数据库组件抽象为 Java 对象,因此它的事务与数据库中所做的更改特别相关。 A transaction may be made up of one or many writes to various database tables that are all committed once the operation is completed.一个事务可能由对各种数据库表的一次或多次写入组成,一旦操作完成,这些写入就会全部提交。 Rolling back the transaction, eg f there are any errors during the operation, allows all the changes to be undone.回滚事务(例如,如果操作期间出现任何错误)允许撤消所有更改。

Spring春天

At its lowest level Spring is a application framework for managing configuration and dependencies between objects.在最底层, Spring是一个应用程序框架,用于管理对象之间的配置和依赖关系。 In addition it also provides an interface for managing higher level services that are used in modern applications such as databases, messaging services, MVC frameworks and transactions.此外,它还提供了一个接口,用于管理现代应用程序中使用的更高级别的服务,例如数据库、消息服务、MVC 框架和事务。

Spring is designed to be used as an all-encompassing master of objects and services within your application, so its concept of a transaction is at a higher level than the database specific transactions that hibernate concerns itself with. Spring 旨在用作应用程序中对象和服务的无所不包的主人,因此它的事务概念比休眠所关注的特定于数据库的事务处于更高级别。 Spring Transactions are designed to give you fine grained control of all your transactional resources while abstracting away the often messy coding required to co-ordinate the transactions. Spring Transactions旨在为您提供对所有事务资源的细粒度控制,同时抽象出协调事务所需的通常凌乱的编码。

@Transactional

Spring provides a few different methods for using transactions - among others there xml based aspects, coding to the API and annotation based declarative transactions. Spring 提供了几种使用事务的不同方法——其中包括基于 xml 的方面、API 编码和基于注释的声明性事务。 The annotation based transactions are handy because you dont need to add the transaction management boilerplate code to your app (even using PlatformTransactionManager via the API has quite a bit of coding overhead).基于注释的事务很方便,因为您不需要将事务管理样板代码添加到您的应用程序中(即使通过 API 使用 PlatformTransactionManager 也有相当多的编码开销)。

So basically what happens with @Transactional is that at runtime spring scans your code base for @Transactional classes and methods and wraps them up in the transaction specific management code, based on what you have configured via the annotation.所以基本上@Transactional发生的事情是,在运行时 spring 扫描您的代码库以查找 @Transactional 类和方法,并根据您通过注释配置的内容将它们包装在特定于事务的管理代码中。 So a method like this:所以一个这样的方法:

@Transactional(propagation = REQUIRES_NEW, rollbackFor = {Exception.class})
public void saveAndSendMessage(Foo foo) throws Exception {
    dbManager.save(foo);
    Bar bar = transform(foo);
    jmsSystem.send(bar);
}  

can have spring set up a new transaction for the database and jms system, and co-ordinate them without needing to add all the specific tx management code automagically.可以让 spring 为数据库和 jms 系统设置一个新的事务,并协调它们,而无需自动添加所有特定的 tx 管理代码。

Coding level deference编码级别差异

Spring春天

In Spring, we can perform the transaction as below在 Spring 中,我们可以执行如下事务

@Transactional(readOnly=”false”)
public int insert(int studentId, String name, int courseId) {
    int outcome = 0;
    outcome = studentDao.insert(studentId, name);
    if (outcome > 0) {
   // re-intialize
        outcome = 0;
        outcome = studentCourseDao.insert(studentId, courseId);
    }
   return outcome;
}

After seeing the @Transactional, the Spring IOC container is going to perform the transaction.看到@Transactional后,Spring IOC容器就要执行事务了。 If both the operation successfully, then commit operation will be performed.如果两个操作都成功,那么commit操作就会被执行。 If any operation failed then rollback operation will be performed.如果任何操作失败,则将执行回滚操作。

Hibernate休眠

In Hibernate we can perform the transaction as below在 Hibernate 中,我们可以执行如下事务

    public int insert(Student student, Course course) {
      //it is a flag driven transaction
    boolean flag = false;
    Transaction transaction = null;
    Session session = null;
    SessionFactory sessionFactoryRepo = null;
    try {
        sessionFactoryRepo = SessionFactoryRepo.getsessionFactory();
        session = sessionFactoryRepo.openSession();
        // here we are creating the transaction object
        transaction = session.beginTransaction();

        int outcome = 0;
        outcome =session.save(student);
        if (outcome > 0) {
          // re-intialize
            outcome = 0;
            outcome = session.save(course);
        }
        flag = true;
        return outcome;
    } catch (Exception e) {
        // TODO: handle exception
    }
    finally {
        if (flag == true) {
            transaction.commit();
        } else
            transaction.rollback();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM