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();}

        }

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.