jpa on a Desktop SWING Application

谁说胖子不能爱 提交于 2019-11-30 21:26:32
kunal

As I understand, the question boils down to whether you should open EntityManager and store its reference globally and access the same instance everywhere in the application.

I think that should be okay if your application is small to medium size. Just be cautious that database connection (hence session/entityManager) may drop due to various factors. And don't do this with transactions (ie dont open them in beginning and commit in end). Keep transactions as fine grained as possible.

There have been various discussion where more experienced people discussed about it, you can follow that here : for and counter argument on this SO question - Session management using Hibernate in a Swing application

Also see this on the same topic.

Here is a sample desktop application created by a committer of hibernate. Its bit old, you can get the idea.

And finally this is great article for understanding of general JPA concepts for desktop application.

After re-thinking my design, i decided to change it as follows:

  • create a 'permanent' EM when the application starts, and keep it open until the application shutdowns. permanentEM will be used to find/refresh entities when needed (for fetching lazy relationships for example ...).
    In order to ensure an efficient management of memory by the WEAK refrence-mode, i'll avoid to permanently reference permanentEM's managed entities.
  • create a 'temporary' EM to load the 'permanent' data, that are necessary for the start of the application. Once the data loaded close that temporary EM, to detach all the loaded-in-memory data.
  • create a new 'temporary' EM, for each persist/merge/remove transaction, and close it once the transaction commits.

Since its a SE application, your may use the embedded database. I know H2 normally allow one thread visit, so if your are in the same developing environment and want to avoid the headache concurrence control of entity.

my suggestion is that encapsulate the your service call in one thread and assign this thread a entitymanager.

don't allow other threads to use entities , then define data access interface which can transfer data from entity to other objects in a proper data structure .

in one world, i think it is better to put all the entities in one entity manager domain and isolate them from other thread.

have you looked at http://docs.jboss.org/hibernate/core/4.0/manual/en-US/html/transactions.html#transactions-basics-issues. I think it would be wise to read the documentation there before proceeding using sessions object for too much time. I guess the better approach is to use the session to do a simple unit of work (for example : the CRUD operations).

Hope it helps!!.

Greetings.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!