multithreading - Getting LazyInitializationException "could not initialize proxy - no Session" when running a transaction in a background thread -
multithreading - Getting LazyInitializationException "could not initialize proxy - no Session" when running a transaction in a background thread -
i have unusual problem:
say have 2 entity classes, e.g. container
, containedobject
. container
has @onetomany
relationship containedobject
.
when getting contained objects directly, works fine, when running background thread, "could not initialize proxy - no session".
example:
@component public class { @autowired private containerrepository _repo; public void doinforeground() { container container = _repo.findone(42l); // suppose 42 exists container.getcontainedobjects().size(); // succeeds } public void submittobackground() { completablefuture<void> f = completablefuture.supplyasync(() -> doinbackground()); } private void doinbackground() { container container = _repo.findone(42l); container.getcontainedobjects().size(); // throws lazyinitializationexception } }
the containerrepository
pagingandsortingrepository
. running doinforeground
succeeds, submittobackground
throws well-known lazyinitializationexception
"could not initialize proxy - no session"
it seems if no transaction started or closed fast. annotating of methods @transactional
not help either.
is not possible utilize spring-jpa in background threads or additional magic needed?
1) need readonly transaction lazy collections.
2) suppose @transactional doesn't work on local methods because when phone call local method phone call implementation directly, not proxy object created spring.
if it's case there @ to the lowest degree 2 choices:
1) switch aspectj
<tx:annotation-driven mode="aspectj" proxy-target-class="true"/>
2) create transaction manually using transactiontemplate within doinforeground()
: http://simplespringtutorial.com/springprogrammatictransactions.html
multithreading spring hibernate jpa
Comments
Post a Comment