@RestController methods seem to be Transactional by default, Why?

前端 未结 2 1643
天涯浪人
天涯浪人 2021-02-13 17:27

Using Spring boot 1.3.1

I don\'t understand why @RestController are Transactionnal by default. I haven\'t found anything saying so in the docs.

Example which pus

相关标签:
2条回答
  • 2021-02-13 17:59

    One-to-one relations are always eagerly fetched. Judging by method names book.getAuthor().getFirstname(), book->author and author->firstName are such relations. LazyInitializationException will only occur for lazy collections.

    0 讨论(0)
  • 2021-02-13 18:00

    In addition to MirMasej answers, there is one more thing: Spring Boot will automatically register an OpenEntityManagerInViewInterceptor when the following conditions are true:

    • you have a web application
    • you use JPA

    Both conditions are true in your case. This interceptor holds the entity manager open for the whole duration of a request. The auto configuration occurs in the class JpaBaseConfiguration.

    If you don't want that behaviour, you can add the following property to your application.properties file:

    spring.jpa.open-in-view=false
    

    Btw. this behaviour is completely independent of transactions, it's only related to the lifecycle of the entity manager. You can still have two separate transactions and no LazyInitializationException, if both transactions have the same underlying entity manager instance.

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