Skip to content

Instantly share code, notes, and snippets.

@craigew
Created September 22, 2013 13:01
Show Gist options
  • Save craigew/6659684 to your computer and use it in GitHub Desktop.
Save craigew/6659684 to your computer and use it in GitHub Desktop.
Helper class to hide the JPA scaffolding
public class DataAccess<T extends BaseEntity> {
private Class<T> entityClass;
protected long add(T object){
EntityManagerFactory factory = Persistence.createEntityManagerFactory("JPAIntroduction");
EntityManager em = factory.createEntityManager();
em.getTransaction().begin();
em.persist(object);
em.getTransaction().commit();
long id=object.getId();
em.close();
factory.close();
return id;
}
protected void update(T object){
EntityManagerFactory factory = Persistence.createEntityManagerFactory("JPAIntroduction");
EntityManager em = factory.createEntityManager();
em.getTransaction().begin();
em.merge(object);
em.getTransaction().commit();
em.close();
factory.close();
}
protected T findByPrimaryKey(int id) {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("JPAIntroduction");
EntityManager em = factory.createEntityManager();
T returnObject = em.find(getEntityClass(), id);
em.close();
factory.close();
return returnObject;
}
protected Class<T> getEntityClass() {
return entityClass;
}
protected void setEntityClass(Class<T> entityClass) {
this.entityClass = entityClass;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment