Created
September 22, 2013 13:01
-
-
Save craigew/6659684 to your computer and use it in GitHub Desktop.
Helper class to hide the JPA scaffolding
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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