Monday, 25 May 2020

GenericDAO


import java.util.Map;

public interface GenericDao<E, K> {

  long countAll(Map<String, K> params);

  E create(E e);

  void delete(K id);

  E find(K id);

  E update(E e);

}




import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

public abstract class GenericDaoImpl<E, K> implements GenericDao<E, K> {

  @PersistenceContext  protected EntityManager em;

  private Class<E> type;

  public GenericDaoImpl() {
    Type t = getClass().getGenericSuperclass();
    ParameterizedType pt = (ParameterizedType) t;
    type = (Class) pt.getActualTypeArguments()[0];
  }


  @Override  public long countAll(final Map<String, K> params) {

    final StringBuffer queryString = new StringBuffer(
        "SELECT count(o) from ");
    queryString.append(type.getSimpleName()).append(" o ");
    //queryString.append(this.getQueryClauses(params, null));
    final Query query = this.em.createQuery(queryString.toString());

    return (Long) query.getSingleResult();
  }

  @Override  public void delete(final K id) {
    this.em.remove(this.em.getReference(type, id));
  }

  @Override  public E find(final K id) {
    return (E) this.em.find(type, id);
  }

  @Override  public E create(E o) {
    return null;
  }

  @Override  public E update(E o) {
    return null;
  }
}



import com.abc.Employee;


public interface EmployeeDAO extends GenericDao<Employee, Long> {

  long count();
}



import javax.enterprise.context.ApplicationScoped;
import javax.inject.Named;

@ApplicationScoped@Named("EMPDAO")
public class EmployeeDAOImpl extends GenericDaoImpl< Employee, Long> implements EmployeeDAO {
  @Override  public long count() {
    return this.em        .createQuery("SELECT COUNT(e.id) from Employee e", Long.class).getSingleResult();
  }


}



import javax.transaction.Transactional;

public interface EmployeeService {

  @Transactional  Long getEmployeeCountCount();

}




import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.inject.Named;

@ApplicationScopedpublic class EmployeeServiceImpl implements EmployeeService {

  @Inject  @Named("EMPDAO")
  EmployeeDAO empDAO;

  @Override  public Long getEmployeeCountCount() {
    return empDAO.count();
  }
}