Should EntityManaer be Closed in a Desktop Application Environment

Hi All,
I'm developing a desktop application with persistence api to connection to database. The application consists of two simple classes Order and Customer, where Customer is used as a field in Order. There is a ManyToOne relationship from Order to Customer and a OneToMany relationship from Customer to Order.
I have another class DBManager for managing all the database activities. All the methods in the class will create an entityManager and close the entityManager once they finish their own operation. An example method is as following:
public void addOrder(Order order) throws Exception
        try {
            entityManager = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT).createEntityManager();
            entityManager.getTransaction().begin();           
            entityManager.persist(order);
            entityManager.getTransaction().commit();
        } finally {
            if (entityManager.isOpen())
                entityManager.close();
    }As all entity instances will become detached once the entity manager is close. If I execute the above method, I'll receive an error saying that "Cannot persist detached object.", where the object refers to the Customer object stored in the Order.
I found that there are two ways to fix this problem, I can either merge the Customer object back to the context as following:
public void addOrder(Order order) throws Exception
        try {
            entityManager = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT).createEntityManager();
            entityManager.getTransaction().begin();
            order.setCustomer(entityManager.merge(order.getCustomer()));
            entityManager.persist(order);
            entityManager.getTransaction().commit();
        } finally {
            if (entityManager.isOpen())
                entityManager.close();
    }or I can leave the entityManager unclosed after any operation as following:
public void addOrder(Order order) throws Exception
            entityManager = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT).createEntityManager();
            entityManager.getTransaction().begin();           
            entityManager.persist(order);
            entityManager.getTransaction().commit();
    }Both ways would work but I'm not sure which one is the best practice to handle the situation. I know that in EJB environment the entityManager should never be closed, but according to article http://java.sun.com/developer/technicalArticles/J2SE/Desktop/persistenceapi/, entityManager should always be closed when it is no longer needed. I'm therefore very confused about which way to go. Can anyone please give me some advice on that?
Thanks in advance. You help would be greatly appreciated.
Edited by: EWL on Feb 18, 2008 4:37 PM

There are a couple of combining usage issues that are providing the problem. The issue is not specifically with you closing the EM but that combined with your usage of the persist() api. This test case would have the same issue in an EJB environment even if you were not closing the EM.
When using the persist() api you are depending on the behaviour that managed objects are ignored by the persist when infact you should be using multiple APIs depending on the state of the Entities that your application is interacting with.
The best approach is to interact with the EM within your application code. This allows you to share the same EM across all of a particular business call or logical application transaction. This could be wrapped within a DBManager but you would need to expose the concept of transactions to the application. This ensures you can track the lifecycle state of the Entities involved while allowing you to easily manage the EM resource.
If your architecture requires the DBManager pattern you have developed then you should only use persist() on Entities that you know to be new and merge() otherwise. In the example you have provided you could simply swap out persist() for merge() in your addOrder method (without the additional customer merge) and the code should work as you expect allowing you to close the EM.
You will need to close() or clear() the EM at some point within your application. Otherwise you are sure to run out of memory.
--Gordon                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

Similar Messages

  • I have flash professional cc and I need air for desktop application with .exe or .air that should contain all swf's and captive air runtime in one Installer only . I don't want to install separate adobe air runtime .

    I need Air for desktop application either in .exe or in .air with embedded captive runtime just like .apk . I don't want to install adobe air separate . everything should come in installer
    I have adobe flash professional cc development tool , let me know whether I have to go with other development tool???
    your reply will  increase my confidential level
    please anyone can help me to solve this problem
    Thanks&regards
    Niranjan

    Adobe Flash Professional CC manual
    1) Create new project
    2) Configure your Project properties
    3) Embed runtime, so you users can use Adobe AIR without pre-installed Adobe AIR runtime
    4) After publishing you will receive %APP_NAME%.app folder that contain your project files

  • Cannot open Forms in online or desktop application

    When I try to access my form either through the online interface or the Windows desktop application, the message "Loading Form File... " appears breifly (<5 seconds) and then the application freezes.  I saw a similar port earlier today and the Adobe staff replied asking for the form URL.  The URL for my form is:
    https://adobeformscentral.com/?f=wAUrf74fB112*CaqBwseMg
    This form is currently closed.
    Thank you for your help.

    Sorry you're having trouble. I've tweaked the form, so hopefully you should be able to open now. But let me know if you still seeing the problem.
    And we are in progress deploying the update to prevent this happening in the future.
    Thank you,
    Roman

  • Developing desktop applications for windows

    Hello
    I am currently doing a final year project which is an encryption software for the company that i did my placement with. i have done the core part of the program but i need to know how to make it look professional. i need to be able to have it as an installable desktop application (Only for Windows), with an icon provided by me which is used when files are encrypted using the application. i have no idea how to achieve this effect and i seek knowledge.
    thanks in advance for your help

    There are many levels of professional software in my opinion. There is software that works, meets the requirements and doesn't crash. That's professional in the sense that it does what it is supposed to and does it well. People pay for that even if its green-screen non-GUI based. TONS of stuff still working/written for non-GUI environments and plenty pay for it.
    When related to Java and desktop applications, I feel there is only truly one real way to brag you have written a professional software suite. That is when your application not only adheres to what it should do, but provides a means to extend it without having to wait for major releases, and the UI is VERY consistent, not cluttered, not tons of buttons/menus/dialogs/windows all over the place and the underlying coce of the app is truly written well to make good use of areas of Java such as resources (properly closing files when not using them, returning DB connections when done, using WeakReference of nulling out refs to objects no longer needed). It is very very easy to cause a memory leak in a java application if you do not watch at all times for object refs that are left hanging.
    By extensibility, I mean providing some means of plugging in new pieces of code to enhance the product or fix existing issues (bugs) and providing a simple update facility that can either auto-update, or allow an install to add the update.
    It is exactly these reasons that keep me plugging away on my plugin engine (www.sourceforge.net/projects/genpluginengine) and UI framework built around plugins. While the engine is almost done and is very similar to the Eclipse plugin engine, the UI framework will be ongoing for some time. Making a very professional read-to-run-out-of-the-box free/open-source framework built on high-quality well tested plugins is not easy to accomplish with a couple hours a week and only me and one other doing it. I would love to get more help shortly, adding tons of great features that all developers could benefit from, and soon I will start asking various java boards for help, see if anyone is interested in contributing. The goal is a professional looking, solid underlying code, well/highly tested UI framework that can be used by anyone to quickly build their specifics and not worry about the more common UI application stuff such as file i/o choosers, help, preferences, authentication, access levels/rights, views and editors, and more. With a 3rd project working to add tons of Swing UI components, the final UI framework will provide a number of high-quality components like rounded/shaded/gradient filled panels with shadowing, calendar/date pickers, wizards, and more, again all highly tested to ensure ultimate quality.
    If you are interested, feel free to post back to this response with email, or join up at the above mentioned sourceforge project and start contributing to the mail list.

  • Netbeans Java Desktop Application Problem

    Hi
    I have build a java desktop application via netbeans and it creates a jnlp file to execute this applets however in my project when i press a button on an applet it opens another applet and send some parameter via html file how can i do that in desktop application because it doesnt have html file it only has jnlp file ?
    Thanks

    I guess I didnt make myself clear enough,I dont want to use another applet's public methods I want to execute it
    Lets make a scenario
    assume that I have an applet a and applet b
    on applet a there is a button called open applet b and when somebody press this button applet b will be opened
    Before I was doing that like this
                URL page = new URL("http://www.xxx.edu.tr/~team5/nps/build/giris.html");
                getAppletContext().showDocument(page,"_self");but now I made the project netbeans desktop application so I dont have any html file I only have jnlp and jar files
    so what should I do to maintain opening an applet from another applet?
    Thanks

  • Trouble logging in to desktop application

    Hi,
    I've been a user of Adobe story since the first couple of weeks of it's free trial a year back, but I'm having trouble logging into the desktop application now. Whenever I try to sign in, it gives me the "signing in..." window, but then the window closes and it leaves me on the first page with only two options "learn more" or "sign in."
    Another discussion thread told me to delete the "PrivateEncryptedDatak" keychain from the keychain access application, but that didn't help. I also tried deleting the files in the ELS of the AIR application library (aka just moving them so I could return them in case this didn't solve the problem), and that just prompted me to upgrade my account. After putting the files back into the ELS of the AIR application library, it didn't prompt me to upgrade my account but the previous problem remained.
    I was able to log into the desktop application about 2-3 weeks ago, no problem. I am still able to log onto the application through the browser without a problem either - except for that it doesn't have the changes I made to my scripts 2-3 weeks ago.
    Any help?
    Thanks,
    Michael

    Thanks for your help! I'll go ahead and try that.
    A couple of questions first:
    "Rename/Delete your local DB (keep a copy of it, this is your data you will need to restore it) ( It can be found at OSX:  /Users/username/Library/Preferences/ com.adobe.AdobeStory.4875E02D9FB21EE389F73B8D1702B320485DF8CE.1 If Libraryfolder in not visible then follow the steps listed on this page (http://osxdaily.com/2011/07/22/access-user-library-folder-in-os-x-lion /) to reach to library folder)"
    There is also a com.adobe.AdobeStory.4875E02D9FB21EE389F73B8D1702B320485DF8CE.1.plist file. Should I delete this too or just the com.adobe.AdobeStory.4875E02D9FB21EE389F73B8D1702B320485DF8CE.1 folder?
    "Ideally now AIR application is only for the subscribed users but in case it was already being used that user should be able to use it in offline mode. If none of these solutions work out we can help you extract your data from your local DB."
    -Does this mean that I will no longer be able to use the desktop application online? A friend of mine who started using the adobe story with me around the same time (a year ago when adobe was only offering story for free) and he is still able to use his desktop application online. If I can only use the desktop application offline, how will it ever sync with the browser version?
    Thanks!

  • Questions on deploying Java desktop applications

    Hello,
    I have searched the forums and been unable to find the information I need. I am not sure this is the appropriate forum to post at but had to start somewhere!
    I have a Java desktop application which has only been used internally at my organization for R&D. We are now working with our legal folks on setting up various licensing options. The funding organization today said that they wanted the software set up such that deploying it externally would have behaviors such as:
    * preventing one CD being used to install on multiple machines,
    * preventing someone from copying the installed software from one machine to another,
    * have a way for the software to "expire" after a set amount of time.
    I have never had to deploy software externally before (nor does it seem has anyone else at my organization - we do science R&D) and am at a loss as to how to best do this. I have googled around a bit but not found any solutions. Has anyone here done this and could perhaps give me some pointers?
    Much Thanks,
    Keri

    kgoorley wrote: Hello,
    I have searched the forums and been unable to find the information I need. I am not sure this is the appropriate forum to post at but had to start somewhere!
    Given you new not only to deployment, but also
    posting to these forums, I will take the opportunity
    to point out that I let this post be for a couple of
    days since in had no Dukes assigned. To my
    eye, dukes indicate how important a question is
    to whoever asked it, and I do not generally have
    time to answer questions that are not important.
    You can add dukes to a thread at any time.
    kgoorley wrote: ..licensing options. ..
    * preventing one CD being used to install on multiple machines,
    * preventing someone from copying the installed software from one machine to another,
    * have a way for the software to "expire" after a set amount of time.
    Web start apps. are usually deployed directly off
    a server/internet site. Although deployment off CD
    is theoretically possible, it is uncommon.
    The basic answer to all your questions as asked is 'no'.
    However, if the legal people can take a slightly different
    line, and that server/site has some 'active' element to it
    (e.g. it is generated using servlets), there might be other
    options worth considering.
    The basic approach would be not to sell licenses
    per machine, but per 'use', in the sense that if
    I were to sell you a license, it would be for 'nn users',
    rather than 'nn machines'. This means that if you
    had a license for 'two' users (let's call them Bob
    and Harriet), both Bob and Harriet could use any
    PC in the organization to use the software,
    but once they were both logged in, no further
    users of the software would be allowed.
    The way to achieve this is to have the application
    'phone home' to the server and tell it the
    username(/password). Every 2-3 minutes,
    the app. should get back to the server and
    confirm it is 'still running..'. If the app. cannot
    reach the server, it reports a problem to the
    user, and exits.
    If the server does not get a 'still running' confirmation
    in a time longer than that few minutes, it assumes
    the app. is off-screen, and frees that 'licence slot'.
    The reason to keep letting the server know it is
    there, is that if Harriet were to be logged in, and
    Bob accidentally trips over the power cord and
    drops Harriet's computer in a screaming heap,
    her app. will never have the chance to 'log out'
    and inform the server to free the slot.
    As such, it is important to allow her to log-in again in
    'a few minutes' (which is probably about the amount
    of time it will take her machine to reboot, and chide
    Bob for his oafish carelessness).
    Using this system, the first & second requirements
    above become redundant - as it is not the number of
    PC's that we care about - just the number of users.
    The third requirement could easily be handled on
    the server-side, checking licenses as users
    log-in, and confirming that license is still valid.
    Edited by: AndrewThompson64 on Sep 27, 2007 7:30 AM

  • How to add a CSV file to a desktop application and access it?

    I'm writing a desktop application for looking up phone numbers (this numbers are stored in a .CSV file). Where should I put the file in the project and how to access it? I intend to put it in the project and open it in a buffered reader!
    Thanks!

    The best place to put application data is probably user.home, as described in the [Store Application Settings and Components|http://sdnshare.sun.com/view.jsp?id=2305] post at SDNShare.
    If those listings are still messed up, try these alternate renderings of [AppStore.java|http://pscode.org/fmt/sbx.html?url=/test%2FAppStore.java&col=2&fnt=2&tab=2&ln=0] & [AppStoreDemo.java|http://pscode.org/fmt/sbx.html?url=/test%2FAppStoreDemo.java&col=2&fnt=2&tab=2&ln=0].

  • Can you wrap a Muse export in Adobe Air to make a desktop application?

    Hello,
    I was just wondering if it is possible to wrap a Muse HTML folder (whole export) in Adobe Air to make a desktop application? I have managed to wrap the business catalyst URL that Muse gives you temporarily and made a desktop application. As this is temporary is it possible to wrap the entire project (HTML)?
    I'm very new to this so i hope this all makes sense.
    Thanks in advance,
    SPolly

    You are not wasting your time. It can be done...
    In order to wrap C++ for use by C, you must write wrapper functions declared with 'extern "C"' linkage for every C++ method you intend to call directly from C. This must be done using a C++ compiler. Once linked into a new library, any C exectuable or C library should be able to link this new library and call the wrapper functions you have declared 'extern "C"'.
    If you still need more help, I would advise you to post in a C++ language forum perhaps. Best of luck, not that you should need it though... -Ralph

  • Sorry, we couldn't open...Error opening office documents from SharePoint 2013 in the desktop applications

    Sorry, we couldn't open...Error opening office documents from SharePoint 2013 in the desktop applications        
    One of our Managers encounters the error 'A problem occurred while accessing the Office document cache.  Do you want to repair this problem?'
    Then When he says yes it give a warning that the cache will be backed up and replaced
    Then it says 'A new office document Cache has been created...'
    Then it loads this cache with an error
    Then After all that the next time he tries to open the document it says  is encountered "Sorry, we couldn't open 'URL."
    We have Reinstalled office 2013 on the users PC repaired the cache numerous times
    Followed -  http://office.microsoft.com/en-gb/word-help/manually-rename-the-office-document-cache-HA101848838.aspx
    Updated Lync to 2013 leaving Access as the only office 2010 application (required for legacy systems access)
    Repair installed office 2010 and office 2013 again
    The SharePoint site has been added to the trusted sites list and the set up assistant run from office 365
    And the issue remains the Same all other users including some who also have Access 2010 for legacy systems access have no Issues OS is windows 7 32 Bit browser is IE 9
    Office 365 said
    Reply by Rachel Zhang MSFT Support
    Hi Alex,
    From your description, I notice that the issue is related to Office client. We would like to help you, but I’m sorry that our forum does not focus on this scenario and has limited resources regarding it. However, we have a dedicated support forum where
    the support engineers will help you with the issues about Office client:
    Microsoft Office Community:
    http://answers.microsoft.com/en-us/office/forum/office_2013_release?tm=1365567547805
    Feel free to sign in to the Office community and click Participate->Ask a Question to post the question with the relevant information.
    Microsoft Office Community:  
    Feel free to sign in to the Office community and click to post the question with the relevant information.
    Office team said
    Hello Alex,
    Thank you for posting your query in Microsoft Office Community.

    Check if other excel works fine
    Do you have any script\macro in excel file
    Check if all application pool on all servers are running
    both office and IE should be same build (64 or 32 bit)
    what is the error message in ULS log and Event viewer
    If this helped you resolve your issue, please mark it Answered

  • How to create desktop application (AIR) splash screen FB 4.7 ?

    Hi.  I am using Flash Builder 4.7 and with the tutorials and the API documentation on Flex by Adobe I can't seem to find a good solution for creating a Splash Screen for an Adobe AIR Desktop application.  I have found some results for mobile applications but I didn't go into those because I am developing for the desktop.  However if some of the moblie results are valid for porting to desktop I will give them a shot.
    Can anyone point me in the right direction?
    Thanks in advance.
    P.S.  If I port to mobile, I will be porting to Android

    Did you try the newly released SDK from official page, rather than labs? I would also suggest running FB with Java 1.6, if you have it on Java 1.7 - FB4.7 is known to yield some quirks with new java VMs.
    Flash Builder is developed on top of Eclipse platform, which is basically a pluggable architecture - nothing wrong with that. Number of files do not really affect the overall application performance. In general you should not touch that, unless you really know what you doing and can manage all the dependencies on your own. I agree, though, that's is quite unfortunate that Adobe decided to hide the AIR SDK deep inside plugins, instead dragging it out to a top-level folder, where it's visible and available for change. It was possible with Flex SDK configured externally, so why not here?

  • Database in java desktop applications

    0 vote down star
    I am making a desktop application in java and using MS Access asdata base. I want that if i run the setup of the application the database should be created on client machine because there can be different client using the application
    How to do it? please explain me in detail.. thanks

    Path means where ever you want and have rights to put it locally. If you're going to hard code a location into your project, then yes, that does mean the same as your development, otherwise, you'll need to save some configuration string for db location.

  • What data binding framework to use for EJB(JPA) - Swing desktop application

    Hi!
    I am developing EJB server application which mostly uses the same entities and session EJB's both for web and for desktop user interface. While JSF is working nicely, I am stuck with necessity to make decision with data binding framework to use for desktop application - I investigated:
    - JSR295 reference impementation at java.net (beans binding)
    - Eclipse JFace
    - JSR295 implementation at kenai.com (better beans binding)
    - JGoodies binding
    At present I like JGoodies, but I am not sure whether I am not missing something - I guess - large enterprises should develop a lot of desktop applications as well and what binding framework they are using?

    user454720 wrote:
    At present I like JGoodies, but I am not sure whether I am not missing something - I guess - large enterprises should develop a lot of desktop applications as well and what binding framework they are using?No, not really. I create them sometimes but they are service tools, not part of the main application framework. Generally you keep everything on the server, web based - this keeps it secure, accessible and contained. With all the web 2.0 javascript toolkits available nowadays you can go quite far creating a desktop experience in a browser, with limitations.

  • Java or C++ for desktop applications

    Help needed!
    We are a team of 5 programmers in a state agency who deal with federal contracts. About 70% of the applications we build are desktop applications. One of the team members strongly believes that learning C++ instead of Java would strengthen our positions. He strongly believes that Java is not cut out for desktop applications and Java is ideal only for web applications. None of us are very familiar with C++ and so we are intending to take classes in C++. (We are all Visual Foxpro, VB group currently). I have one year of programming with Java (web applications) I still don't want to give up on Java that easily. Well my question is - Is that member in the team right in saying that Java is for web and not for desk top. Can any expert give me a good comparison and so we can move on the right track.
    Thanks for the help in advance!
    suman

    Java can work fine for a desktop application, don't listen to him. Here's what you've got to consider:
    1. Tool set: One strength of java is its strong set of standardized tools. You can probably find great sets of C++ tools too, though, but this is a major factor.
    2. Speed of development: This depends somewhat on the strength and maturity of the toolset you are using, but in general, I think that java is faster to develop for 3 reasons: (1) because it smoothes over some of the inconsistancies between systems - you don't have to get as involved in the gritty details. (2) Java can often tell you exactly what line number your program is bombing, and in every case, it will give you a specific message about what kind of error you had (nullpointer, array out of bounds, etc vs 'Syntax Error') (3) Garbage collection
    3. Familiarity with language: Obviously if you've got to learn something new, that takes time.
    4. App performance: Java is probably going to be bigger, in terms of what has to be installed on the machine in order to run your app, and marginally slower than C++. It will almost certainly require a lot more memory to run well. Before you freak out about it being slower than C++ though, you should consider what kind of performance your app needs. If it's doing 3D rendering, C++ is probably going to be better. If most of it is UI components, and the back end processing is not that intensive, Java could be what you want

  • Handling different screen resolutions by a desktop application

    Hi,
    I recently tried to make a desktop app using basic javafx layouts and controls. I made it using borderpanes, gridpanes and stackpanes. I had a base of borderpane, on which all my controls were placed on grid, but it looked lame, so i inserted a colorful rectangle in between the background and controls using stackpane. Everything was wonderful on my system, but when i gave it to a friend to check out what i had made, it just wasn't the way i had made it on my system.
    The background was as it should have been(it was because the scene was kept at screen resolution) but the rectangle and the controls were displaced, and the reason was my friend has a laptop with higher resolution than mine. I tried to fix things up, removing the hard coding for the placements and using an ratio of the screen resolution, but no matter how much i tried, something or the other seemed to be out of place. For ex, on a page where i had one big rectangle, inside which there are two small rectangles and each rectangle have a gridpane with controls. All of them are stacked together using Stackpane.
    I'd blame all to the stackpane, but i chose it coz my requirement demanded it.
    Any suggestions on how to make an desktop application which can handle all resolutions, and the best practices that must be followed and kept in mind, while designing a desktop app.
    Thanks,
    Abhi

    one example you can find in the image below, where i had set the message perfectly in my system and opening it in another system, the message is not placed correctly.
    http://i37.tinypic.com/hv8mtl.png
    Hope now yu understand my problem.

Maybe you are looking for

  • Are there any other internet/online channels for Vista media center?

    Hi, I was just wondering if there are any other internet/online channels I can get for Vista Media Center? I only have about 9 at the moment, and would like preferby free ones. I don't have satelite or cable tv so would like online ones, is there any

  • How to setup SMTP server  in PC so as to send mails using JavaMail

    Hi, From forums i got it cleared that we can use JavaMail to send emails. I also got two sample codes about getting it done. But in the code its asks address of the host of SMTP server. I dont have any SMTP server. But i am writing a Library Applicat

  • How can I get the Playlists in my iTunes Account on my Mac onto my iPhone?

    How can I get the Playlists in my iTunes Account on my Mac onto my iPhone? I have 5 or 6 different Playlists when I go to iTunes on my ac, but I have none on my iPhone. Why don't they synch?

  • All_tab_columns and all_tab_cols

    Hey guys, I've come across this problem, what can I do? I know what all_tab_cols and all_tab_columns are supposed to have information about all the tables in the database and that they're very useful. The problem is, all_tab_cols will show that a cer

  • How to drag and drop files between two JFileChooser

    Sir i want to drag and drop files between two JFileChooser i don't know how to do that. So is there any reference code for that so that i can able to do it. I have enabled setDragEnabled(true) for both the jfilechooser now i don't now how to drop fil