My application is heavily using thread pool, even a method of a class may be executed in another thread using aspectj advice.
This brings me a problem of how to design my database entity using Hibernate JPA implementation, especially with one-to-many, many-to-many and so forth. The problem is my application uses session-per-thread pattern that EntityManager is stored in ThreadLocal, so the entity obtained in one thread is frequently passed to another thread. If I have any one-to-many like mapping in entity, the lazy fetching won't work since the entity is out of persistence.
The workaround I see is calling merge() to attach entity to thread's entity manager before any access to lazy fetching entity, but this requires a wrapper class for entity which call merge() in every getter of associated entity. This has a drawback that if I change some fields of the entity but not want to merge to persistence right now, calling a getter will screw up.
I did some research but not got any better solution. I was wondering this should be a common practice for threadpool oriented application. there must be a best practice pattern.
another way is never using such one-to-many facility but that introduces much boring coding burden.
Does anyone have a better idea?
|