I am working on REST and JPA technology and want to design Service and Dao layer generically. I want to follow the decouple rule for each layer. So that in future at any point of time these layer can be changed if required without much modification. So to do the same for DAO layer I am following Factory pattern.
Please have a look what i did till now.
public abstract class AbstractDao {
@PersistenceUnit(name = "Services")
private EntityManagerFactory factory;
public AbstractDao() {
this.factory = Persistence.createEntityManagerFactory("Services");
}
public void save(AbstractEntity entity) {
EntityManager em = getEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
em.persist(entity);
tx.commit();
}
public void delete(AbstractEntity entity) {
getEntityManager().remove(entity);
}
public List<AbstractEntity> findAll() {
CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
CriteriaQuery<AbstractEntity> cq = cb.createQuery(AbstractEntity.class);
Root<AbstractEntity> from = cq.from(AbstractEntity.class);
cq.select(from);
TypedQuery<AbstractEntity> q = getEntityManager().createQuery(cq);
List<AbstractEntity> allitems = q.getResultList();
return allitems;
}
private EntityManager getEntityManager() {
EntityManager em = factory.createEntityManager();
return em;
}
}
So this the design what I used for DAO layer. But not sure is it the right approach or it can be much better like AbstractFactory patter or etc.
Now come to REST Service layer where I am accessing this DAO layer for CRUD.
So this the way how I am accessing the DAO layer on Service layer. But again I am thinking to way some other better way to access this DAO layer. One more thing I want to ask, would it be good idea if I introduce business layer and follow like this.
Client -> Service Layer-> Business Layer -> DAO Layer
Could someone help me to design the different layer of project.
Thanks in advance.
Aucun commentaire:
Enregistrer un commentaire