1.spring.jpa.open-in-view
在使用spring boot web 時,會自動引入一個配置:spring.jpa.open-in-view=true,這個配置可以保證在controller層不會出現no session的問題,如果設置爲false,那麼在controller層就會出現no session的問題。
a. no session出現的原因
在controller層會出現no session是因爲jpa懶加載,在service層只是一個延遲加載對象(只有id,實體類的其他值都是null),到了controller層需要獲取其他值時,事務已經結束,session也已經被關閉,所以在controller層調用會出現no session。
b. spring.jpa.open-in-view的作用
spring.jpa.open-in-view
java.lang.Boolean
Default: true
Register OpenEntityManagerInViewInterceptor.
Binds a JPA EntityManager to the thread for the entire processing
of the request.
即:這個配置就是在controller層就打開EntityManager,由controller層控制session的開啓和關閉,這樣controller層就可以操作對象,而不會出現no session。OpenEntityManagerInViewInterceptor這個攔截器實現session的開啓和關閉。
ps:此配置建議關閉。
2.hibernate.enable_lazy_load_no_trans
如果關閉上述配置,那麼在懶加載時controller層獲取實體類屬性值就會出現no session錯誤,這時候在jpa配置文件中,設置hibernate.enable_lazy_load_no_trans值爲true,就可以解決no session的錯誤了。
也可以在application.yml中配置spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true。
這個配置的意思就是在沒有事務的情況下允許懶加載。