Skip to content

Instantly share code, notes, and snippets.

@topriddy
Created September 16, 2017 16:20
Show Gist options
  • Save topriddy/9a588bd2cc45c7e92a2f5361f385cce3 to your computer and use it in GitHub Desktop.
Save topriddy/9a588bd2cc45c7e92a2f5361f385cce3 to your computer and use it in GitHub Desktop.
Sample Hibernate AbstractDAOImpl utility class from an old project 2014.
package ng.myproject.backend.dao.impl;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import lombok.extern.log4j.Log4j;
import ng.myproject.backend.dao.Dao;
import ng.myproject.backend.entities.DomainObject;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Projections;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
@SuppressWarnings("unchecked")
@Log4j
@Repository
public abstract class AbstractDaoHibernateImpl<T extends DomainObject> implements Dao<T> {
private Class<T> domainClass;
@Autowired
SessionFactory sf;
public AbstractDaoHibernateImpl(Class<T> domainClass) {
this.domainClass = domainClass;
}
@Transactional
@Override
public void delete(T object) {
getSession().delete(object);
}
@Transactional
@Override
public T load(Serializable id) {
return (T) getSession().get(domainClass, id);
}
@Override
@Transactional
public void save(T object) {
//object = (T) getSession().merge(object);
getSession().saveOrUpdate(object);
}
@Transactional
public List<T> findAll() {
Criteria criteria = getSession().createCriteria(domainClass);
criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
return criteria.list();
}
@Transactional
public List<T> findAll(int start, int size) {
Criteria criteria = getSession().createCriteria(domainClass);
criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
criteria.setFetchSize(start);
criteria.setFetchSize(size);
return criteria.list();
}
@Transactional
public int countAll() {
Criteria criteria = getSession().createCriteria(domainClass);
criteria.setProjection(Projections.rowCount());
return ((Long) criteria.uniqueResult()).intValue();
}
/* finders utils */
public <T> T executeQueryUniqueResult(String query) {
return (T) executeQueryUniqueResult(query, new ArrayList());
}
public <T> T executeQueryUniqueResult(String query, Object param) {
List paramList = new ArrayList();
paramList.add(param);
return (T) executeQueryUniqueResult(query, paramList);
}
public <T> T executeQueryUniqueResult(String query, List paramsList) {
T result = null;
Session session = null;
try {
session = getSession();
Query q = session.createQuery(query);
if (paramsList != null) {
for (int i = 0; i < paramsList.size(); i++) {
q.setParameter(i, paramsList.get(i));
}
}
result = (T) q.uniqueResult();
} catch (Exception ex) {
log.error("", ex);
}
return result;
}
public <T> T executeQueryUniqueResult(String query,
Map<String, Object> paramsMap) {
T result = null;
Session session = null;
try {
session = getSession();
Query q = session.createQuery(query);
if (paramsMap != null) {
for (String key : paramsMap.keySet()) {
q.setParameter(key, paramsMap.get(key));
}
}
result = (T) q.uniqueResult();
} catch (Exception ex) {
log.error("", ex);
}
return result;
}
public <T> List<T> executeQuery(String query, Object param) {
List paramList = new ArrayList();
paramList.add(param);
return executeQuery(query, paramList);
}
public <T> List<T> executeQuery(String query, Object param, int start,
int size) {
List paramList = new ArrayList();
paramList.add(param);
return executeQuery(query, paramList, start, size);
}
public <T> List<T> executeQuery(String query, List paramsList) {
List<T> entityList = new ArrayList<T>();
Session session = null;
try {
session = getSession();
Query q = session.createQuery(query);
if (paramsList != null) {
for (int i = 0; i < paramsList.size(); i++) {
q.setParameter(i, paramsList.get(i));
}
}
entityList = q.list();
} catch (Exception ex) {
log.error("", ex);
}
return entityList;
}
/*
* Note Hibernate doesnt allow Date and TimeStamp parameters to be set
* dynamically without specifying the types
*/
public <T> List<T> executeQuery(String query, int start, int size) {
return executeQuery(query, new ArrayList(), start, size);
}
public <T> List<T> executeQuery(String query, List paramsList, int start,
int size) {
List<T> entityList = new ArrayList<T>();
Session session = null;
try {
session = getSession();
Query q = session.createQuery(query);
if (paramsList != null) {
for (int i = 0; i < paramsList.size(); i++) {
q.setParameter(i, paramsList.get(i));
}
}
q.setFirstResult(start);
q.setMaxResults(size);
entityList = q.list();
} catch (Exception ex) {
log.error("", ex);
}
return entityList;
}
public <T> List<T> executeQuery(String query, Map<String, Object> paramsMap) {
List<T> entityList = new ArrayList<T>();
Session session = null;
try {
session = getSession();
Query q = session.createQuery(query);
if (paramsMap != null) {
for (String key : paramsMap.keySet()) {
q.setParameter(key, paramsMap.get(key));
}
}
entityList = q.list();
} catch (Exception ex) {
log.error("", ex);
}
return entityList;
}
public <T> List<T> executeQuery(String query) {
List<T> entityList = new ArrayList<T>();
Session session = null;
try {
session = getSession();
Query q = session.createQuery(query);
entityList = q.list();
} catch (Exception ex) {
log.error("", ex);
}
return entityList;
}
public Object getObjectById(Class record, Long recordId) {
Session session = null;
Object object = null;
try {
session = getSession();
object = session.get(record, recordId);
} catch (Exception ex) {
log.error("", ex);
}
return object;
}
/*
* Note Hibernate doesnt allow Date and TimeStamp paramters to be set
* dynamically without specifying the types
*/
public <T> List<T> executeQuery(String query,
Map<String, Object> paramsMap, int start, int size) {
List<T> entityList = new ArrayList<T>();
Session session = null;
try {
session = getSession();
Query q = session.createQuery(query);
if (paramsMap != null) {
for (String key : paramsMap.keySet()) {
q.setParameter(key, paramsMap.get(key));
}
}
q.setFirstResult(start);
q.setMaxResults(size);
entityList = q.list();
} catch (Exception ex) {
log.error("", ex);
}
return entityList;
}
@Override
public Collection getAllRecordsByParameterId(Class manyClass, Class oneClass, java.lang.Long parameterId, int pageIndex, int pageSize) {
java.lang.String strOneClass = getProcessedClassName(oneClass);
java.lang.String hql = "SELECT c FROM " + manyClass.getName() + " c WHERE c." + strOneClass + ".id=" + parameterId;
org.hibernate.Query query = getSession().createQuery(hql);
query.setFirstResult(pageIndex);
query.setMaxResults(pageSize);
Collection returnCol = (Collection) query.list();
return returnCol;
}
@Override
public Object getSingleRecordByParameterId(Class singleClass, Class oneClass, java.lang.Long parameterId) {
java.lang.String strOneClass = getProcessedClassName(oneClass);
java.lang.String hql = "SELECT c FROM " + singleClass.getName() + " c WHERE c." + strOneClass + ".id=" + parameterId;
org.hibernate.Query query = getSession().createQuery(hql);
return query.uniqueResult();
}
private java.lang.String getProcessedClassName(java.lang.Class clazz) {
java.lang.String retString = clazz + "";
retString = retString.substring(retString.lastIndexOf("."));
retString = retString.substring(1, 2).toLowerCase() + "" + retString.substring(2);
return retString;
}
public Session getSession() {
return sf.getCurrentSession();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment