Hi all would like to ask question about JPA syntax ,which of this 2 versions of code syntaticly better and safer?

    public static Prices getPriceById(int id){

        EntityManager em = DBUtil.getEntityManagerFactory().createEntityManager();
        return em.find(Prices.class, id);

    }

or this version :

  public static Prices getPriceById(int id){

        EntityManager em = DBUtil.getEntityManagerFactory().createEntityManager();
        try{
            Prices pr = em.find(Prices.class, id);
        return  pr;
        }
        finally{em.close();}

        }

Recommended Answers

All 2 Replies

Both versions appear to fail this guide. http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-141388.html

Now discounting that, if both work then good stuff. But the arguments about try/catch are legendary.
https://www.google.com/search?q=should+java+use+try+catch

My view? What are the coding standards your company mandates or your client demands?
Hint? The person with the gold sets the rules.

Those two are not equivalent. In the first you seem to hope that allowing your entity manager to be garbage collected is enough to be sure you have no resource leaks. The second guarantees that the em is closed properly. The first is bad coding, the second is much better. Remember that you are responsible for any resources you create.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.