问题
Is there any standard way (or substitute to Open Session [EntityManager] in View
) for usage of classes that depend on Lazy Initialization (fetch = FetchType.LAZY)
of entities in
following two use-cases:
In the JUnit test cases
In quartz jobs
For both the above scenarios OSIV pattern will not work as no web request enters the system. How to get Lazy Loading work in such situations?
PS: Spring's OpenEntityManagerInViewFilter
and OpenEntityManagerInViewInterceptor
are both web request oriented.
- I can not prefetch all such relations/entites by doing a dummy
get
just to load it before session is closed in the repository(DAO). - I know, for JUnit I can manually open/close EM in
@Before
/@after
. But am looking for something more elegant and standard.
Rerference : LazyInitializationException due to no session defined in "parent" application context in Hibernate 3 in a moduled Spring application using annotations
回答1:
Transactions are what you need. Open a transaction, fetch the data, manipulate it, then close the transaction when you're done. Spring binds the EntityManager
lifecycle to that of the transaction, and holds it open as long as you need.
Spring Transaction Management is a significant subject in itself, but using it is really quite straightforward. See the docs.
来源:https://stackoverflow.com/questions/7017374/openentitymanagerinview-equivalent-for-junit-and-quartz-jobs