简体   繁体   English

在休眠中使用@Transactional

[英]Using @Transactional with hibernate

I am using hibernate for the REST API. 我正在为REST API使用休眠模式。 Right now all the transactions are handled by explicitly calling beginTransaction and transaction.commit. 现在,所有事务都通过显式调用beginTransaction和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. 我正在寻找使用@Transactional而不是所有的beginTransactions并提交事务。 Could someone tell me how can I integrate @Transactional in my hibernate. 有人可以告诉我如何将@Transactional集成到休眠状态。 I am using mysql for querying the database. 我正在使用mysql查询数据库。

You can annotate your query method with @Transactional so you get your transaction opened, commited and closed when your method ends. 您可以使用@Transactional注释查询方法,以便在方法结束时打开,提交和关闭事务。

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. 注意隔离级别https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/transaction/annotation/Transactional.html#isolation-- ),因为它指示了Spring何时会为您的交易创建一个新会话,或仅使用已打开的会话。

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. 您可以将Spring Framework与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. 好处是spring管理Hibernate会话的内容以及我们必须在hibernate中手动管理的所有低级内容,例如粒度提交等。这是此示例。 this is older repository so uses older version of Spring and Hibernate but you can upgrade it here 这是较旧的存储库,因此使用较旧的Spring和Hibernate版本,但您可以在此处升级

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

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