hibernate session.flush with spring @transactional

后端 未结 2 1955
旧时难觅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: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 ;)

提交回复
热议问题