Search code examples
javaspring-boothibernatespring-data-jpaspring-data

What is a transaction boundary in hibernate


I have 2 questions related to each other

Q1 What exactly is a transaction boundary in hibernate/Spring Data JPA. I am new to JPA , so please give a very basic example so I can understand as I tried to read multiple blogs but still not very clear.

Q2 And on top of it, what does this mean-

In hibernate, persist() method guarantees that it will not execute an INSERT statement if it is called outside of transaction boundaries, save() method does not guarantee the same.

What is outside and inside of a transaction boundary and how executions are performed outside boundaries?


Solution

  • A transaction is a unit of work that is either executed completely or not at all.

    Transactions are fairly simple to use in a typical relational database. You start a transaction by modifying some data. Every modification starts a transaction, you typically can't avoid it. You end the transaction by executing a commit or rollback.

    Before your transaction is finished your changes can't be seen in other transactions (there are exceptions, variations and details). If you rollback your transaction all your changes in the database are undone. If you commit your changes your changes become visible to other transactions, i.e. for other users connected to the same database. Implementations vary among many other things if changes become visible only for new transactions or also for already running transactions.

    A transaction in JPA is a database transaction plus additional stuff. You can start and end a transaction by getting a Transaction object and calling methods on it. But nobody does that anymore since it is error prone. Instead you annotate methods with @Transaction and entering the method will start a transaction and exiting the method will end the transaction. The details are taken care of by Spring.

    The tricky part with JPAs transactions is that within a JPA transaction JPA might (and will) choose to delay or even avoid read and write operations as long as possible. For example when you load an entity, and load it again in the same JPA transaction, JPA won't load it from the database but return the same instance it returned during the first load operation. If you want to learn more about this I recommend looking into JPAs first level cache.