package +zoccolo+.jpa.dao.impl; import java.util.ArrayList; import java.util.Collection; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.PersistenceException; import javax.persistence.Tuple; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Expression; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import javax.persistence.Query; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.springframework.transaction.annotation.Transactional; import +zoccolo+.jpa.Filter; import +zoccolo+.jpa.Order; import +zoccolo+.jpa.OrderBuilder.OrderType; import +zoccolo+.jpa.PaginatedFilter; import +zoccolo+.jpa.SearchParameter; import +zoccolo+.jpa.dao.GenericDao; /** * Implementation of the interface for dao management.
* IMPORTANT - Reference to the persistence context JPA is set in this implementation. * * @param */ public abstract class GenericDaoImpl implements GenericDao { public static final Logger logger = LogManager.getLogger(GenericDaoImpl.class); @PersistenceContext(unitName="+rail+EntityManagerFactory") protected EntityManager em; protected String generateDebugParameters(List> parameters) { if (parameters == null || parameters.size() == 0) { return "[]"; } StringBuffer paramsDebug = new StringBuffer("["); for (SearchParameter parameter : parameters) { paramsDebug.append(" ").append(parameter.getName()).append("=").append(parameter.getValue()); } paramsDebug.append("]"); return paramsDebug.toString(); } protected List createOrderClauseList(CriteriaBuilder cb, Root root, Order[] order) { List orderList = new ArrayList<>(); if (order == null) return orderList; for (Order ord : order) { if (OrderType.ASC.toString().equals(ord.getAsc())) { orderList.add(cb.asc(root.get(ord.getOrder()))); } else { orderList.add(cb.desc(root.get(ord.getOrder()))); } } return orderList; } @Override @Transactional(rollbackFor=PersistenceException.class) public T create(T entity) { if (logger.isDebugEnabled()) logger.debug("Create entity: " + entity); em.persist(entity); em.flush(); return entity; } @Override @Transactional(rollbackFor=PersistenceException.class) public T update(T entity) { // Check if instance is detached if (!em.contains(entity)) { if (logger.isDebugEnabled()) logger.debug("Update entity: " + entity); entity = em.merge(entity); } em.flush(); return entity; } @Override @Transactional(rollbackFor=PersistenceException.class) public void remove(T entity) { if (logger.isDebugEnabled()) logger.debug("Remove entity: " + entity); // check if instance is detached if (!em.contains(entity)) { entity = em.merge(entity); } em.remove(entity); em.flush(); } @Override public T findUniqueById(Class entityClass, Integer id) { if (logger.isDebugEnabled()) logger.debug("findUniqueById(" + entityClass.getName() + ", " + id + ")"); T result = em.find(entityClass, id); return result; } @Override public T findUniqueById(Class entityClass, Long id) { if (logger.isDebugEnabled()) logger.debug("findUniqueById(" + entityClass.getName() + ", " + id + ")"); T result = em.find(entityClass, id); return result; } @Override public T findUniqueById(Class entityClass, String id) { if (logger.isDebugEnabled()) logger.debug("findUniqueById(" + entityClass.getName() + ", '" + id + "')"); T result = em.find(entityClass, id); return result; } @Override public Collection findListBy(Class entityClass, String fieldName, Class fieldClass, Object fieldValue) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery cq = cb.createQuery(entityClass); Root root = cq.from(entityClass); Predicate predicate = cb.equal( root.get(fieldName).as(fieldClass), fieldValue); cq.where(predicate); TypedQuery tq = em.createQuery(cq); if (logger.isDebugEnabled()) logger.debug("Start of findListBy(" + entityClass + "," + " '" + fieldName + "'" + " " + fieldClass + "" + " '" + fieldValue + "')"); Collection results = tq.getResultList(); return results; } @Override public List like(Class fieldClazz, String fieldName, Class valueClazz, String fieldValue) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery cq = cb.createQuery(fieldClazz); Root root = cq.from(fieldClazz); Predicate predicate = cb.like( (Expression)cb.upper( root.get(fieldName).as(valueClazz)), "%"+ fieldValue.toUpperCase()+"%"); cq.where(predicate); TypedQuery tq = em.createQuery(cq); List results = tq.getResultList(); return results; } @Override public Collection findAll(Class entityClass, Order ... order) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery cq = cb.createQuery(entityClass); Root root = cq.from(entityClass); cq.orderBy(createOrderClauseList(cb, root, order)); TypedQuery tq = em.createQuery(cq); if (logger.isDebugEnabled()) logger.debug("Start of findAll(" + entityClass + ")"); Collection result = tq.getResultList(); return result; } @Override public Boolean exists(Class entityClass, Long id) { if (logger.isDebugEnabled()) logger.debug("Start of exists(" + entityClass + ", " + id + ")"); T result = em.find(entityClass, id); return result == null ? false : true; } @Override public Boolean exists(Class entityClass, String id) { if (logger.isDebugEnabled()) logger.debug("Start of exists(" + entityClass + ", " + id + ")"); T result = em.find(entityClass, id); return result == null ? false : true; } /** * Metodo da implementare per effettuare un'inizializzazione di una entity * con caricamenti di dati lazy. Per default restituisce la entity * inalterata. * * la HibernateUtils.initialize(). * * @param entity * @return */ protected T load(T entity) { return entity; } protected void setPagination(TypedQuery tq, Filter filter) { if (filter instanceof PaginatedFilter) { PaginatedFilter pfilter = (PaginatedFilter) filter; int firstResult = pfilter.getFirstResult(); int pageSize = pfilter.getPageSize(); if (logger.isTraceEnabled()) logger.trace("Range (" + firstResult + ", " + pageSize + ")"); tq.setFirstResult(firstResult); tq.setMaxResults(pageSize); } } @Override public Long count(Class entityClass) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery cq = cb.createQuery(Long.class); Root root = cq.from(entityClass); cq.select(cb.count(root)); TypedQuery tq = em.createQuery(cq); Long result = tq.getSingleResult(); return result; } @Override public Long count(Class entityClass, Filter filter) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery cq = cb.createQuery(Long.class); Root root = cq.from(entityClass); List predicates = new ArrayList<>(); if (!filter.getParams().isEmpty()) { predicates.add(getLikePredicate(cb, root, filter.getParams())); } if (predicates.size() > 0) { cq.where(cb.and(predicates.toArray(new Predicate[] {}))); } cq.select(cb.count(root)); TypedQuery tq = em.createQuery(cq); Long result = tq.getSingleResult(); return result; } @Override @SuppressWarnings("unchecked") public List fetch(Class entityClass, Filter filter, Order... order) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery cq = cb.createTupleQuery(); Root root = cq.from(entityClass); List predicates = new ArrayList<>(); if (!filter.getParams().isEmpty()) { predicates.add(getLikePredicate(cb, root, filter.getParams())); } if (predicates.size() > 0) { cq.where(cb.and(predicates.toArray(new Predicate[] {}))); } cq.select(cb.tuple(root)); cq.distinct(true); cq.orderBy(createOrderClauseList(cb, root, order)); TypedQuery tq = em.createQuery(cq); setPagination(tq, filter); List results = tq.getResultList(); List loadedResults = new ArrayList(); for (Tuple result : results) { loadedResults.add(load((T) result.get(0))); } return loadedResults; } @Override public boolean existsByFilename(Class entityClass, SearchParameter fileName) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery cq = cb.createQuery(Long.class); Root root = cq.from(entityClass); Predicate p = cb.equal(root.get(fileName.getName()).as(String.class), fileName.getValue()); cq.where(p); cq.select(cb.count(root)); TypedQuery tq = em.createQuery(cq); Long result = tq.getSingleResult(); return result > 0; } private Predicate getLikePredicate(CriteriaBuilder cb, Root root, List> parameters) { List orPredicates = new ArrayList(); for (SearchParameter parameter : parameters) { orPredicates.add(cb.like(cb.upper(root.get(parameter.getName()).as(String.class)), "%" + parameter.getValue().toUpperCase() + "%")); } return cb.or(orPredicates.toArray(new Predicate[] {})); } @SuppressWarnings("unchecked") @Override public List oneColumnQuery(final String string) { Query qu = em.createQuery(string); List sE = qu.getResultList(); return sE; } @Override public List manyColumnQuery(final String string) { Query qu = em.createQuery(string); List sE = qu.getResultList(); return sE; } @Override public Object findByPrimary(Class entityClass, Object chiave) { Object x = em.find(entityClass, chiave); return x; } }