Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package org.jlego.core.dao;
- import java.lang.reflect.ParameterizedType;
- import java.util.Iterator;
- import java.util.List;
- import java.util.Map.Entry;
- import java.util.Set;
- import javax.persistence.EntityManager;
- import javax.persistence.OptimisticLockException;
- import javax.persistence.PersistenceContext;
- import javax.persistence.Query;
- import org.jlego.core.CoreException;
- import org.jlego.core.CoreExceptionConstants;
- import org.jlego.core.dao.Criteria.CriteriaOrder;
- import org.jlego.util.EntityUtil;
- import org.springframework.dao.DataIntegrityViolationException;
- import org.springframework.transaction.annotation.Transactional;
- /**
- * Base DAO (Data Access Object). Perform routine DAO tasks such as insert,
- * update, and delete <br/>
- * Example:
- * <br/>
- * <code>
- * public class AnotherDao extends BaseDaoImpl <Long, User> implements BaseDao {<br/>
- * <br/>
- * }<br/>
- * </code>
- *
- * @author Ali Irawan
- * @version 1.0
- * @param <K>
- * parameter as Key type
- * @param <E>
- * parameter as Entity type
- */
- public class BaseDaoImpl<K, E> implements BaseDao<K, E> {
- protected Class<E> entityClass;
- protected String className;
- @PersistenceContext
- protected EntityManager entityManager;
- /**
- * Default constructor for BaseDAO
- */
- @SuppressWarnings("unchecked")
- public BaseDaoImpl() {
- ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
- this.entityClass = (Class<E>) genericSuperclass.getActualTypeArguments()[1];
- String completeName = this.entityClass.getName();
- // Get name for the entity
- String entityName = this.entityClass.getAnnotation(javax.persistence.Entity.class).name();
- if (entityName == null || entityName.equals("")) {
- this.className = completeName.substring(completeName.lastIndexOf('.') + 1);
- } else {
- this.className = entityName;
- }
- }
- /**
- * insert data to persistence
- *
- * @param entity
- * object to be inserted
- * @throws CoreException
- */
- @Transactional
- public void persist(E entity) {
- try {
- entityManager.persist(entity);
- } catch (DataIntegrityViolationException e) {
- String entityClassName = entity.getClass().getName();
- String tableName = EntityUtil.getTableName(entityClassName);
- throw new CoreException(CoreExceptionConstants.DATA_INTGR_VIOLATION, entityClassName + "(" + tableName + ")");
- }
- }
- /**
- * update data to persistence
- *
- * @param entity
- * object to be updated
- * @throws CoreException
- */
- @Transactional
- public E merge(K id, E entity) {
- E entityF = findByPk(id);
- if (entityF == null) {
- throw new CoreException(CoreExceptionConstants.ID_NOT_FOUND);
- } else {
- try {
- entityF = entityManager.merge(entity);
- entityManager.flush();
- entityManager.clear();
- } catch (OptimisticLockException ole) {
- String entityClassName = entity.getClass().getName();
- String tableName = EntityUtil.getTableName(entityClassName);
- throw new CoreException(CoreExceptionConstants.MERGE_FAIL_DATA_NOT_UPTODATE, entityClassName + "(" + tableName + ")");
- }
- return entityF;
- }
- }
- /**
- * delete data from persistence
- *
- * @param id
- * primary key to be deleted
- * @throws CoreException
- */
- @Transactional
- public void remove(K id) {
- E entity = findByPk(id);
- if (entity == null)
- throw new CoreException(CoreExceptionConstants.ID_NOT_FOUND, (Object) null);
- else {
- try {
- entityManager.remove(entity);
- entityManager.flush();
- entityManager.clear();
- } catch (OptimisticLockException ole) {
- String entityClassName = entity.getClass().getName();
- String tableName = EntityUtil.getTableName(entityClassName);
- throw new CoreException(CoreExceptionConstants.REMOVE_FAIL_DATA_NOT_UPTODATE, entityClassName + "(" + tableName + ")");
- }
- }
- }
- /**
- * Search data from persistence using specified ID
- *
- * @param id
- * primary key that uniquely identify the object
- * @return return the object defined by Key, if no data match the method
- * returns null
- */
- public E findByPk(K id) {
- return entityManager.find(entityClass, id);
- }
- /**
- * Query all data and return in a List
- *
- * @return list of data with specific entity type
- */
- @SuppressWarnings("unchecked")
- public List<E> findAll() {
- List<E> allEntities = entityManager.createQuery("select e from " + className + " e").getResultList();
- return allEntities;
- }
- public long count() {
- return (Long) entityManager.createQuery("select count(e) from " + className + " e").getSingleResult();
- }
- /**
- * Check whether the list is empty
- *
- * @param list
- * list to be checked
- * @return true is the list is empty, neither false
- */
- @SuppressWarnings("rawtypes")
- protected boolean isEmptyList(List list) {
- return list == null || list.size() == 0;
- }
- /**
- * Find using criteria
- */
- @SuppressWarnings("unchecked")
- public E find(Criteria criteria) {
- Query query = this.criteriaToQuery(criteria);
- List<E> list = (List<E>) query.getResultList();
- if (list.size() == 0) {
- return null;
- }
- return list.get(0);
- }
- /**
- * Find all using criteria
- */
- @SuppressWarnings("unchecked")
- public List<E> findAll(Criteria criteria) {
- Query query = this.criteriaToQuery(criteria);
- List<E> list = (List<E>) query.getResultList();
- if (list.size() == 0) {
- return null;
- }
- return list;
- }
- /**
- * Convert criteria to object query
- * @param criteria criteria object
- * @return query object
- */
- private Query criteriaToQuery(Criteria criteria) {
- // example criteria: e.refNo = :refNo and e.refType = :refType
- StringBuffer sql = new StringBuffer();
- sql.append("SELECT e FROM " + className + " e");
- sql.append(" WHERE 1=1 AND ");
- sql.append(criteria.getCondition());
- // apply order by is specified
- if (criteria.getOrdersBy().size() != 0) {
- sql.append(" ORDER BY ");
- Set<Entry<String, CriteriaOrder>> orderEntrySet = criteria.getOrdersBy().entrySet();
- Iterator<Entry<String, CriteriaOrder>> it = orderEntrySet.iterator();
- while (it.hasNext()) {
- Entry<String, CriteriaOrder> entry = it.next();
- sql.append("e." + entry.getKey());
- sql.append(" " + ((entry.getValue() == CriteriaOrder.CRITERIA_ASC) ? "ASC" : "DESC"));
- if (it.hasNext())
- sql.append(", ");
- }
- }
- Query query = entityManager.createQuery(sql.toString());
- // apply parameters
- Set<Entry<String, Object>> entrySet = criteria.getParameters().entrySet();
- Iterator<Entry<String, Object>> t = entrySet.iterator();
- while (t.hasNext()) {
- Entry<String, Object> temp = (Entry<String, Object>) t.next();
- query.setParameter(temp.getKey(), temp.getValue());
- }
- // apply startRow, the default value is 0, start from the first record
- query.setFirstResult(criteria.getStartRow());
- // apply max result if specified, -1 means no max result specified
- if (criteria.getMaxResult() != -1) {
- query.setMaxResults(criteria.getMaxResult());
- }
- return query;
- }
- /**
- * Create query with native query
- */
- public Query createNativeQuery(String sqlString) {
- return entityManager.createNativeQuery(sqlString);
- }
- /**
- * Create query with JPQL
- */
- public Query createQuery(String query) {
- return entityManager.createQuery(query);
- }
- /**
- * Create query with Named Query
- */
- public Query createNamedQuery(String queryName) {
- return entityManager.createNamedQuery(queryName);
- }
- /**
- * Flush all cached to database
- */
- public void flush() {
- entityManager.flush();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement