开发者

Best way to do database access in a Java desktop application

开发者 https://www.devze.com 2023-02-07 11:49 出处:网络
I\'ve been working in Glassfish 3, JPA and Java EE 6.In a web container you can just inject the Entity Manager into an EJB and let that handle your transactions, rollbacks, etc.What do I do in a deskt

I've been working in Glassfish 3, JPA and Java EE 6. In a web container you can just inject the Entity Manager into an EJB and let that handle your transactions, rollbacks, etc. What do I do in a desktop application. Obviously that does not work. I know I would still use JPA for ORM. But would I create an EntityMangerFactory 开发者_JS百科and then create an Entitymanager from that? Would I have to handle my transactions manually? It would great if I could see some sample applications. Thanks!


EntityManagerFactory entityManagerFactory = 
     Persistence.createEntityManagerFactory("DS");
em = entityManagerFactory.createEntityManager();

You have to handle transactions, by calling em.getTransaction.begin() and em.getTransaction.commit(), if you don't use the spring-framework or something else.


Well i suggest to try using Spring +JPA, there you do not need a container ,it is just the application context and you can configure transactions there. You will not take care of the transactions ,just annotate your methods that you want to be @Transactional.


You could use Spring, this will bring you the plesent you know from JEE6 to desktop applications. (Of course it is not 100% the same!)


Another option could be to use so called Embeddable EJB Container. It could provide you same services as injection, CMT etc which you might be accustomed to.


I've built a 2-tier Java Swing client using Hibernate and Swing, and I will never do it again. If I had to rebuild it today, I would use raw JDBC queries, or maybe a very thin ORM mapping framework like iBatis.

The reason that Hibernate (and I assume other JPA implementations, although my experience is only with Hibernate) is so different in a desktop environment is 1) because objects tend to have a much longer lifespan on the desktop, and 2) it's very hard to know when an object will be accessed, so correct transaction handling for lazy loading is problematic.

The web request-response paradigm is fundamentally transactional, so it's very easy to demarcate your transactions there. On the desktop, every keypress, even just a MouseMovedEvent, could potentially trigger a database query or lazy load, so it's much harder to know when to initiate and commit transactions.

Error handling and object refreshing is a big problem, since objects tend to have a much longer life (often for the duration of the application launch). In Hibernate, exceptions are non-recoverable, which means that you're supposed to reload everything from the db. This is fine on the web, but definitely not fine when you have thousands of objects embedded in various models throughout your GUI.

0

精彩评论

暂无评论...
验证码 换一张
取 消