What is a Transaction in JPA?

Sungju Kim·2024년 8월 27일

Sparta_Coding_Camp_TIL

목록 보기
24/53

The more fundamental way of using JPA is to explicitly call the EntityManager, start a transaction, insert entities is persistence context and to commit them to the database. It is commonly known by many users that the EntityManager object, as the name suggests manages the entities so they can be inserted and removed from the persistence context.

HOWEVER, then what is a transaction, often provided in the annotation @Transactional?

The image below, shows two methods, createSchedule and createScheduletwo; While both methods are identical in functionality, the later version is the more fundamental way of coding the previous one.

From the createScheduletwo method, we can see that it creates a transaction in line #35, initializes it in line #37, ueses it to commit in line #45, and eventually closes it in line #48. This suggest that the transaction object indicates when the start of a script of modification begins (via begin), when it is applied to the database (via commit), and when it ends (via close).

💡Also, its important to note that the @Transactional annotation will rollback() if an error occurs during the life span of its transaction as shown in line #47. However, this can be changed and customized based on what you put in the catch statement if you are using JPA like createScheduletwo. 💡

profile
Fully ✨committed✨ developer, always eager to learn!

0개의 댓글