hibernate session.flush with spring @transactional

后端 未结 2 1985
旧时难觅i
旧时难觅i 2021-02-20 04:34

I am using Spring and Hibernate in my application and using Spring Transaction.

So I have a service layer with annotation @Transaction on methods and DAO la

相关标签:
2条回答
  • 2021-02-20 05:12

    Yes, if you have @Transactional for your DAO method then you need not flush the session manually, hibernate will take care of flushing the session as part of committing the transaction if the operations in the method are successful.

    Check this link to know on how @Transactional works - Spring - @Transactional - What happens in background?

    0 讨论(0)
  • 2021-02-20 05:33

    By default, hibernate stacks its queries so they can be optimized when they are finally executed onto the database.

    The hole point of flush is to flush this stack and execute it in your transaction onto the database. Your leaving the "save" house of the jvm and execute your query on a big strange database.

    This is why you can't select something you've just saved without a flush. It's simply not in the database yet.

    The meaning of commit is ending once transaction and make changes of the database visible for others. Once commit has been executed there's no return possible anymore.

    Frankly I'm not exactly sure if it is a best practice but for normal CRUD operations you should be able to add flush into your dao layer. This way you don't need to worry about it into the service layer.

    If you want java to optimize your transaction then you'll have to add it into your service layer. But remember that you don't need to solve performance issues when there aren't any! Flushes all over your code into the service layer is not good for the code readability. Keep it simple and stupid ;)

    0 讨论(0)
提交回复
热议问题