0

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

        }
3
Contributors
2
Replies
21
Views
9 Months
Discussion Span
Last Post by JamesCherrill
0

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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.