package com.totsp.example.jpa.dao.plain; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import org.apache.log4j.Logger; import com.totsp.example.jpa.dao.IUserDao; import com.totsp.example.jpa.exception.DataException; import com.totsp.example.jpa.model.User; public class UserDao extends BaseDao implements IUserDao { private static final Logger LOG = Logger.getLogger(UserDao.class); private EntityManager manager; public UserDao() { super(); this.manager = emf.createEntityManager(); LOG.debug("userDao constructed"); LOG.debug("EntityManager created"); } public User get(long id) throws DataException { LOG.debug("get invoked - id = " + id); User user = null; try { user = manager.find(User.class, id); } catch (NoResultException e) { LOG.warn(e); } return user; } public User get(String name) throws DataException { LOG.debug("get invoked - name = " + name); User user = null; try { user = (User) manager.createQuery("select a from User a where a.name = ?1").setParameter(1, name).getSingleResult(); } catch (NoResultException e) { LOG.warn(e); } return user; } public List getAll() throws DataException { LOG.debug("getAll invoked"); List users = null; try { users = manager.createQuery("select a from User a").getResultList(); } catch (NoResultException e) { LOG.warn(e); } return users; } public User update(User user) throws DataException { LOG.debug("update invoked - user = " + user); manager.getTransaction().begin(); manager.merge(user); manager.getTransaction().commit(); return user; } public void save(User user) throws DataException { LOG.debug("save invoked - user = " + user); manager.getTransaction().begin(); manager.persist(user); manager.getTransaction().commit(); } public void remove(User user) throws DataException { LOG.debug("remove invoked - user = " + user); manager.getTransaction().begin(); manager.remove(user); manager.getTransaction().commit(); } public void finalize() throws Throwable { LOG.debug("finalize invoked"); try { if (manager != null) { manager.close(); LOG.debug("EntityManager closed"); } } finally { super.finalize(); } } }