简体   繁体   中英

Using @Transactional with hibernate

I am using hibernate for the REST API. Right now all the transactions are handled by explicitly calling beginTransaction and transaction.commit. The transaction is rolled back in case of a failure. I am looking to use @Transactional instead of all the beginTransactions and commit transactions. Could someone tell me how can I integrate @Transactional in my hibernate. I am using mysql for querying the database.

You can annotate your query method with @Transactional so you get your transaction opened, commited and closed when your method ends.

Be careful about isolation levels ( https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/transaction/annotation/Transactional.html#isolation-- ) because it indicates when Spring will create a new session for your transaction, or simply use already opened one.

When you thrown an exception on your method, transaction gets an automatic rollback and you're good :)

You can use Spring Framework with Hibernate Integration. The advantage is spring manages the Hibernate session's and all the low level things that we have to manage manually in hibernate like granular commit etc. Here is the example of this. this is older repository so uses older version of Spring and Hibernate but you can upgrade it here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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