Generic DAO Interface
import java.io.Serializable;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.List;
public interface GenericDao<T, PK extends Serializable> {
public void setClazz(final Class<T> clazzToSet);
public T findById(PK id);
public List<T> findAll();
public void persist(T persistenceObject);
public PK save(T persistenceObject);
public Collection<PK> saveAll(Collection<T> persistenceObject);
public void saveOrUpdate(T persistenceObject);
public void saveOrUpdateBulk(Collection<T> persistenceObject);
public boolean delete(PK id);
public boolean deleteAll(Collection<T> persistenceObject);
public List<T> getNamedQuery(String queryName);
public List<T> getNamedQueryAndNamedParam(String queryName,
String paramName, Object value);
public List<T> getNamedQueryAndNamedParam(String queryName,
String[] paramNames, Object[] values);
public List<T> getNamedQueryPrimaryKeys(String queryName,
String[] paramNames, Object[] values);
public List<T> getNamedQueryWithParamTypes(String queryName,
String[] paramNames, Object[] values, Type[] types);
public List<T> getNamedQueryWithParamTypes(String queryName, Object[] values, Type[] types);
public List getNamedQueryWithParamTypesAndReturn(String queryName, String[] paramNames, Object[] values, Type[] types);
public List<T> getNamedQueryWithEntitiesAndNamedParam(String queryName,
String entity, Object entityValue, String[] paramNames, Object[] paramValues);
public List<String> getNamedQueryWithEntitiesAndNamedParamReturnString(String queryName,
String entity, Object entityValue, String[] paramNames,
Object[] paramValues);
public List<T> getNamedQueryWithTwoEntitiesAndNamedParam(String queryName,
String entity, Object entityValue, String entity2, Object entityValue2, String[] paramNames,
Object[] paramValues);
public List<String> getNamedQueryWithParams(String queryName, String[] paramNames, Object[] paramValues);
public int getNamedQueryWithParamsWithNoReturn(String queryName, String[] paramNames, Object[] paramValues);
public int getNamedQueryWithParamTypesForUpdates(String queryName,
String[] paramNames, Object[] values, Type[] types);
public int insertWithPartition(String queryName,
String[] paramNames, Object[] values, Type[] types);
}
GenericHibernateDao
import java.io.Serializable;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.StatelessSession;
import org.hibernate.Transaction;
import org.hibernate.type.IntegerType;
import org.hibernate.type.CharacterArrayType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
@Repository
@Scope("prototype")
public class GenericHibernateDao<T, PK extends Serializable> implements GenericDao<T, PK> {
private Class<T> clazz;
private static final Logger log = LoggerFactory.getLogger(GenericHibernateDao.class);
@Autowired
private SessionFactory sessionFactory;
public void setClazz(final Class<T> clazzToSet) {
this.clazz = clazzToSet;
}
//@Autowired
public void setSessionFactory(final SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
protected Session getSession() {
return sessionFactory.getCurrentSession();
}
protected StatelessSession getStatelessSession() {
return sessionFactory.openStatelessSession();
}
protected Session getOpenSession() {
return sessionFactory.openSession();
}
@SuppressWarnings("unchecked")
//@Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
@Transactional
public T findById(PK id) {
Object obj = null;
obj = getSession().get(clazz, id);
return (T) obj;
}
@SuppressWarnings("unchecked")
//@Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
@Transactional
public List<T> findAll() {
String queryString = "from " + clazz.getName();
Query query = getSession().createQuery(queryString);
//query.setCacheable(true);
List<T> list = query.list();
return list;
}
@SuppressWarnings("unchecked")
//@Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
@Transactional
public PK save(T persistenceObject) {
Serializable save = getSession().save(persistenceObject);
return (PK) save;
}
public void persist(T persistenceObject) {
Session session = sessionFactory.openSession();
session.beginTransaction();
session.persist(persistenceObject);
session.getTransaction().commit();
}
@SuppressWarnings({ "unchecked", "rawtypes" })
//@Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
@Transactional
public Collection<PK> saveAll(Collection<T> persistenceObject) {
List<Serializable> serializableList = new ArrayList();
for (Iterator<T> iterator = persistenceObject.iterator(); iterator
.hasNext();) {
T o = iterator.next();
Serializable returnObject = getSession().save(o);
serializableList.add(returnObject);
}
return (Collection<PK>) serializableList;
}
//@Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
@Transactional
public void saveOrUpdate(T persistenceObject) {
getSession().saveOrUpdate(persistenceObject);
}
public void saveOrUpdateBulk(Collection<T> persistenceObject) {
Session session = getOpenSession();
Transaction tx = session.beginTransaction();
try {
int i = 0;
for (Iterator<T> iterator = persistenceObject.iterator(); iterator.hasNext();) {
//System.out.println(i);
i++;
session.saveOrUpdate(iterator.next());
if (i % 1000 == 0) {
session.flush();
session.clear();
}
}
tx.commit();
}catch (Exception e) {
if (tx!=null) tx.rollback();
log.error("ERROR ON saveOrUpdateBulk ", e);
} finally {
session.close();
}
}
/*public void saveOrUpdateBulkPartition(String partitionQueryName, Collection<T> persistenceObject) {
Session session = getOpenSession();
Transaction tx = session.beginTransaction();
try {
int i = 0;
for (Iterator<T> iterator = persistenceObject.iterator(); iterator.hasNext();) {
//System.out.println(i);
i++;
session.saveOrUpdate(iterator.next());
if (i % 1000 == 0) {
session.flush();
session.clear();
}
}
tx.commit();
}catch (Exception e) {
if (tx!=null) tx.rollback();
log.error("ERROR ON saveOrUpdateBulk ", e);
} finally {
session.close();
}
}
*/
//@Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
@Transactional
public boolean delete(PK id) {
Object findById = findById(id);
if (findById != null) {
getSession().delete(findById);
return true;
}
return false;
}
@Transactional
public boolean deleteAll(Collection<T> persistenceObject) {
Session session = getOpenSession();
Transaction tx = session.beginTransaction();
int i = 0;
for (Iterator<T> iterator = persistenceObject.iterator(); iterator.hasNext();) {
i++;
session.delete(iterator.next());
if (i % 100 == 0) {
session.flush();
session.clear();
}
}
tx.commit();
session.close();
return true;
}
@SuppressWarnings("unchecked")
//@Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
@Transactional
public List<T> getNamedQuery(String queryName) {
Query query = getSession().getNamedQuery(queryName);
//query.setCacheable(true);
List<T> results = query.list();
return results;
}
@SuppressWarnings("unchecked")
//@Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
@Transactional
public List<T> getNamedQueryAndNamedParam(String queryName, String paramName, Object value) {
Query query = getSession().getNamedQuery(queryName).setString(paramName, value.toString());
//query.setCacheable(true);
List<T> results = query.list();
return results;
}
// This uses open session because if there is a huge amount of data then it cannot be handle normally
@SuppressWarnings("unchecked")
//@Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
@Transactional
public List<T> getNamedQueryWithEntitiesAndNamedParam(String queryName, String entity, Object entityValue, String[] paramNames, Object[] paramValues) {
Session session = getOpenSession();
Transaction beginTransaction = session.beginTransaction();
Query namedQuery = session.getNamedQuery(queryName);
namedQuery.setEntity(entity, entityValue);
for (int i = 0; i < paramNames.length; i++) {
String intValue = paramValues[i].toString();
namedQuery.setParameter(paramNames[i], Integer.parseInt(intValue));
}
List<T> results = namedQuery.list();
beginTransaction.commit();
session.flush();
return results;
}
@SuppressWarnings("unchecked")
//@Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
@Transactional
public List<String> getNamedQueryWithEntitiesAndNamedParamReturnString(String queryName, String entity, Object entityValue, String[] paramNames, Object[] paramValues) {
Query namedQuery = getSession().getNamedQuery(queryName);
namedQuery.setEntity(entity, entityValue);
for (int i = 0; i < paramNames.length; i++) {
String intValue = paramValues[i].toString();
namedQuery.setParameter(paramNames[i], Integer.parseInt(intValue));
}
//namedQuery.setCacheable(true);
List<String> results = namedQuery.list();
return results;
}
// This uses open session because if there is a huge amount of data then it cannot be handle normally
@SuppressWarnings("unchecked")
//@Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
@Transactional
public List<T> getNamedQueryWithTwoEntitiesAndNamedParam(String queryName,
String entity, Object entityValue, String entity2, Object entityValue2, String[] paramNames,
Object[] paramValues) {
Session session = getOpenSession();
Transaction beginTransaction = session.beginTransaction();
Query namedQuery = session.getNamedQuery(queryName);
namedQuery.setEntity(entity, entityValue);
namedQuery.setEntity(entity2, entityValue2);
for (int i = 0; i < paramNames.length; i++) {
String intValue = paramValues[i].toString();
namedQuery.setParameter(paramNames[i], Integer.parseInt(intValue));
}
List<T> results = namedQuery.list();
beginTransaction.commit();
session.flush();
return results;
}
@SuppressWarnings("unchecked")
//@Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
//@Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
@Transactional
public List<T> getNamedQueryAndNamedParam(String queryName, String[] paramNames, Object[] values) {
Query namedQuery = getSession().getNamedQuery(queryName);
for (int i = 0; i < paramNames.length; i++) {
String intValue = values[i].toString();
namedQuery.setParameter(paramNames[i], Integer.parseInt(intValue));
}
//namedQuery.setCacheable(true);
List<T> results = namedQuery.list();
return results;
}
@SuppressWarnings("unchecked")
//@Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
@Transactional
public List<T> getNamedQueryPrimaryKeys(String queryName, String[] paramNames, Object[] values) {
Query namedQuery = getSession().getNamedQuery(queryName);
for (int i = 0; i < paramNames.length; i++) {
String intValue = values[i].toString();
//namedQuery.setParameter(paramNames[i], Integer.parseInt(intValue));
namedQuery.setInteger(paramNames[i], Integer.parseInt(intValue));
}
//namedQuery.setCacheable(true);
List<T> results = namedQuery.list();
return results;
}
@SuppressWarnings("unchecked")
//@Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
@Transactional
public int getNamedQueryWithParamsWithNoReturn(String queryName, String[] paramNames, Object[] values) {
Query namedQuery = getSession().getNamedQuery(queryName);
for (int i = 0; i < paramNames.length; i++) {
String intValue = values[i].toString();
namedQuery.setParameter(i, Integer.parseInt(intValue));
}
//namedQuery.setCacheable(true);
int executeUpdate = namedQuery.executeUpdate();
return executeUpdate;
}
@SuppressWarnings("unchecked")
// @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
@Transactional
public int getNamedQueryWithParamTypesForUpdates(String queryName, String[] paramNames, Object[] values, Type[] types) {
Query namedQuery = getSession().getNamedQuery(queryName);
//namedQuery.setEntity(entity, entityValue);
for (int i = 0; i < paramNames.length; i++) {
if (types[i].equals(Integer.class)) {
Integer value = (Integer) values[i];
namedQuery.setInteger(i, value);
} else if (types[i].equals(String.class)) {
namedQuery.setString(i, (String) values[i]);
} else if (types[i].equals(Date.class)) {
namedQuery.setParameter(paramNames[i], (Date) values[i]);
}
}
int results = namedQuery.executeUpdate();
return results;
}
@Transactional
public int insertWithPartition(String queryName, String[] paramNames, Object[] values, Type[] types) {
Query namedQuery = getSession().getNamedQuery(queryName);
for (int i = 0; i < paramNames.length; i++) {
//System.out.println(values[i]);
if (types[i].equals(Integer.class) && values[i] != null) {
Integer value = (Integer) values[i];
namedQuery.setInteger(i, value);
} else if (types[i].equals(String.class) ) {
namedQuery.setString(i, (String) values[i]);
} else if (types[i].equals(Date.class) && values[i] != null) {
namedQuery.setParameter(i, (Date) values[i]);
} else if (types[i].equals(Character[].class) && values[i] != null) {
//namedQuery.setParameter(i, charArray, CharacterArrayType.INSTANCE );
//namedQuery.setText(i, values[i]);
} else if(values[i] == null){
//namedQuery.setParameter(paramNames[i], values[i] );
namedQuery.setParameter(i, values[i], IntegerType.INSTANCE );
}
}
int results = namedQuery.executeUpdate();
return results;
}
@SuppressWarnings("unchecked")
//@Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
@Transactional
public List<T> getNamedQueryWithParamTypes(String queryName, String[] paramNames, Object[] values, Type[] types) {
Query namedQuery = getSession().getNamedQuery(queryName);
for (int i = 0; i < paramNames.length; i++) {
if (types[i].equals(Integer.class)) {
Integer value = (Integer) values[i];
namedQuery.setParameter(paramNames[i], value);
} else if (types[i].equals(String.class)) {
namedQuery.setParameter(paramNames[i], (String) values[i]);
} else if (types[i].equals(Date.class)) {
namedQuery.setParameter(paramNames[i], (Date) values[i]);
}
}
//namedQuery.setCacheable(true);
List<T> results = namedQuery.list();
return results;
}
@Transactional
public List<T> getNamedQueryWithParamTypes(String queryName, Object[] values, Type[] types) {
Query namedQuery = getSession().getNamedQuery(queryName);
for (int i = 0; i < values.length; i++) {
if (types[i].equals(Integer.class)) {
Integer value = (Integer) values[i];
namedQuery.setParameter(i, value);
} else if (types[i].equals(String.class)) {
namedQuery.setParameter(i, (String) values[i]);
} else if (types[i].equals(Date.class)) {
namedQuery.setParameter(i, (Date) values[i]);
}
}
//namedQuery.setCacheable(true);
List<T> results = namedQuery.list();
return results;
}
@SuppressWarnings("unchecked")
//@Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
@Transactional
public List getNamedQueryWithParamTypesAndReturn(String queryName, String[] paramNames, Object[] values, Type[] types) {
Query namedQuery = getSession().getNamedQuery(queryName);
for (int i = 0; i < paramNames.length; i++) {
if (types[i].equals(Integer.class)) {
Integer value = (Integer) values[i];
namedQuery.setParameter(paramNames[i], value);
} else if (types[i].equals(String.class)) {
namedQuery.setParameter(paramNames[i], (String) values[i]);
} else if (types[i].equals(Date.class)) {
namedQuery.setParameter(paramNames[i], (Date) values[i]);
}
}
//namedQuery.setCacheable(true);
List result = namedQuery.list();
return result;
}
@SuppressWarnings("unchecked")
//@Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
@Transactional
public List<String> getNamedQueryWithParams(String queryName, String[] paramNames, Object[] paramValues){
Query namedQuery = getSession().getNamedQuery(queryName);
for (int i = 0; i < paramNames.length; i++) {
String intValue = paramValues[i].toString();
namedQuery.setParameter(paramNames[i], Integer.parseInt(intValue));
}
//namedQuery.setCacheable(true);
List<String> results = namedQuery.list();
return results;
}
}
Datasoure Configurations in Spring
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="${JDBC_CONNECTION_STRING}" />
<property name="username" value="${DATASOURCE_USER_NAME}" />
<property name="password" value="${DATASOURCE_USER_PASSWORD}" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.x.model" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</prop>
<prop key="hibernate.show_sql">${HIBERNATE_SHOW_SQL}</prop>
<prop key="hibernate.hbm2ddl.auto">false</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.auto_close_session">true</prop>
<!-- below line may be important for some apps for the releasing to work properly -->
<prop key="hibernate.connection.release_mode">after_transaction</prop>
</props>
</property>
<property name="mappingResources">
<list>
<value>named-queries.xml</value>
</list>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory" p:dataSource-ref="dataSource">
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="clientDao" class="com.xxxxxxxxxxdao.GenericHibernateDao">
<property name="clazz" value="com.ls.nix.client.model.Client" />
</bean>
<hibernate-mapping>
<!-- Named queries for Client -->
<query name="Client.findAllByNotNullSalesForceId">
<![CDATA[SELECT c FROM Client c LEFT JOIN FETCH c.clientStatus AS clientStatus]]>
</query>
</hibernate-mapping>
How do you call it
@Autowired
@Qualifier(value = "clientDao")
private GenericDao<Client, Integer> clientDao;