Java tutorial
/*$Id: AbstractBaseDaoImpl.java 14895 2010-02-13 12:49:31Z jens $*/ /* **************************************************************************** * * * (c) Copyright 2006 ABM-utvikling * * * * This program is free software; you can redistribute it and/or modify it * * under the terms of the GNU General Public License as published by the * * Free Software Foundation; either version 2 of the License, or (at your * * option) any later version. * * * * This program is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General * * Public License for more details. http://www.gnu.org/licenses/gpl.html * * * **************************************************************************** */ package no.abmu.common.persistence.hibernate3; import java.io.Serializable; import java.util.Collection; import java.util.List; import no.abmu.common.domain.Entity; import no.abmu.common.persistence.FinderSpecification; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hibernate.Criteria; import org.hibernate.HibernateException; import org.hibernate.LockMode; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.orm.hibernate3.SessionFactoryUtils; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; /** * AbstractBaseDaoImpl. * * @author Erik Romson, erik@zenior.no * @author $Author: jens $ * @version $Rev: 14895 $ * @date $Date: 2010-02-13 13:49:31 +0100 (Sat, 13 Feb 2010) $ * @copyright ABM-Utvikling */ public class AbstractBaseDaoImpl extends HibernateDaoSupport { private static final Log logger = (Log) LogFactory.getLog(AbstractBaseDaoImpl.class); public void saveOrUpdate(Object obj) { Session session = SessionFactoryUtils.getSession(getSessionFactory(), true); logger.info("Updating: " + obj); // Session session = SessionFactoryUtils.getSession(getSessionFactory(), false); try { session.saveOrUpdate(obj); //session.flush(); } catch (HibernateException ex) { throw SessionFactoryUtils.convertHibernateAccessException(ex); } } public void saveOrUpdateNewSession(Object obj) { Session session = SessionFactoryUtils.getSession(getSessionFactory(), true); Session newSession = null; try { newSession = session.getSessionFactory().openSession(session.connection()); newSession.saveOrUpdate(obj); } catch (HibernateException ex) { throw SessionFactoryUtils.convertHibernateAccessException(ex); } finally { if (newSession != null) { try { newSession.flush(); newSession.close(); } catch (HibernateException e) { throw SessionFactoryUtils.convertHibernateAccessException(e); } } } } public void saveOrUpdate(Object[] objs) { Session session = SessionFactoryUtils.getSession(getSessionFactory(), true); try { for (int i = 0; i < objs.length; i++) { Object obj = objs[i]; if (obj == null) { throw new IllegalArgumentException( "Tried to persist a null object. It was in index " + i + " of the array"); } session.saveOrUpdate(obj); } } catch (HibernateException ex) { throw SessionFactoryUtils.convertHibernateAccessException(ex); } } public void delete(Object obj) { Session session = SessionFactoryUtils.getSession(getSessionFactory(), true); try { session.delete(obj); } catch (HibernateException ex) { throw SessionFactoryUtils.convertHibernateAccessException(ex); } } public Object get(Serializable id, Class clazz) { Session session = SessionFactoryUtils.getSession(getSessionFactory(), true); try { return session.load(clazz, id); } catch (HibernateException ex) { throw SessionFactoryUtils.convertHibernateAccessException(ex); } } public Object[] find(String query) { logger.debug("Running HQL query: " + query); List objList = null; Session session = SessionFactoryUtils.getSession(getSessionFactory(), true); try { objList = session.createQuery(query).list(); } catch (HibernateException ex) { throw SessionFactoryUtils.convertHibernateAccessException(ex); } return objList.toArray(new Object[objList.size()]); } /* public Object[] find(String queryStr, Object[] args, Type[] types) { logger.debug("Running HQL queryStr: " + queryStr); List objList = null; Session session = SessionFactoryUtils.getSession(getSessionFactory(), true); try { Query query=session.createQuery(queryStr); query.setParameters(args, types); objList = query.list(); } catch (HibernateException ex) { throw SessionFactoryUtils.convertHibernateAccessException(ex); } return objList.toArray(new Object[objList.size()]); } */ public Object[] findAll(Class clazz) { return find("from " + clazz.getName()); } public List query(String queryString, int firstElementOnPage, int pageSize) { logger.debug("Running HQL query: " + queryString); List objList = null; Session session = SessionFactoryUtils.getSession(getSessionFactory(), true); try { objList = session.createQuery(queryString).setFirstResult(firstElementOnPage).setMaxResults(pageSize) .list(); } catch (HibernateException ex) { throw SessionFactoryUtils.convertHibernateAccessException(ex); } return objList; } public Integer queryCount(String countString) { Integer nrOfElements = null; Session session = SessionFactoryUtils.getSession(getSessionFactory(), true); try { nrOfElements = ((Integer) session.createQuery(countString).iterate().next()); } catch (HibernateException ex) { throw SessionFactoryUtils.convertHibernateAccessException(ex); } return nrOfElements; } public void closeSession() { Session session = null; try { SessionFactoryUtils.getSession(getSessionFactory(), true); } catch (IllegalStateException e) { logger.warn("No session to close", e); return; } releaseSession(session); } public void save(Object obj) { Session session = SessionFactoryUtils.getSession(getSessionFactory(), true); try { session.save(obj); } catch (HibernateException ex) { throw SessionFactoryUtils.convertHibernateAccessException(ex); } } /** * Uses a finder specification to find a collection. * * @param finderSpecification * @return the found objects */ public Collection find(FinderSpecification finderSpecification) { List retLis = null; Session session = SessionFactoryUtils.getSession(getSessionFactory(), true); try { if (finderSpecification instanceof AbstractQueryFinderSpecification) { Query query = ((AbstractQueryFinderSpecification) finderSpecification).createQuery(session); retLis = query.list(); } else if (finderSpecification instanceof AbstractCriteraFinderSpecification) { Criteria criteria = ((AbstractCriteraFinderSpecification) finderSpecification) .createCriteria(session); retLis = criteria.list(); } else { throw new IllegalArgumentException( "Unsupported finder specification " + finderSpecification.getClass().getName()); } } catch (HibernateException ex) { throw SessionFactoryUtils.convertHibernateAccessException(ex); } return retLis; } /** * findSingle. * * @param finderSpecification * @return the found object, null if none was found * @throws IllegalArgumentException if the finder returned more than one */ public Object findSingle(FinderSpecification finderSpecification) { Collection retVal = null; Session session = SessionFactoryUtils.getSession(getSessionFactory(), true); retVal = find(finderSpecification); if (retVal.size() == 0) { return null; } else if (retVal.size() > 1) { throw new IllegalArgumentException( "More than one entity was returned when only one or none was expected."); } return retVal.iterator().next(); } /** * dd. * @param finderSpecification * @return */ public Integer findCount(FinderSpecification finderSpecification) { Integer nrOfElements = null; Long nrOfElementsAsLong = null; Session session = SessionFactoryUtils.getSession(getSessionFactory(), true); try { if (finderSpecification instanceof AbstractQueryFinderSpecification) { Query query = ((AbstractQueryFinderSpecification) finderSpecification).createQueryCount(session); nrOfElementsAsLong = (Long) query.iterate().next(); nrOfElements = nrOfElementsAsLong.intValue(); logger.debug("Count string: " + finderSpecification.toString() + " Returned " + nrOfElements); } else if (finderSpecification instanceof AbstractCriteraFinderSpecification) { throw new UnsupportedOperationException(); } else { throw new IllegalArgumentException( "Unsupported finder specification " + finderSpecification.getClass().getName()); } } catch (HibernateException ex) { throw SessionFactoryUtils.convertHibernateAccessException(ex); } return nrOfElements; } public void reattach(Object obj) { Session session = SessionFactoryUtils.getSession(getSessionFactory(), true); try { session.lock(obj, LockMode.NONE); } catch (HibernateException e) { throw new RuntimeException("Problem reattaching object " + obj.toString(), e); } } public void evictEntities(Collection<? extends Entity> entities) { for (Entity entity : entities) { evictEntity(entity); } } public void evictEntity(Entity entity) { SessionFactory sessionFactory = getSessionFactory(); Session session = SessionFactoryUtils.getSession(sessionFactory, true); try { // Clear session cache e.g. first-level cache session.clear(); // Evict second-level cache sessionFactory.evict(entity.getClass(), entity.getId()); } catch (HibernateException e) { String errorMessage = "Can't evict entity id='" + entity.getId() + "' of class='" + entity.getClass().getName() + "'."; logger.error(errorMessage, e); throw new RuntimeException(errorMessage, e); } } public void evictClasses(Collection<Class<? extends Entity>> clazzes) { for (Class<? extends Entity> clazz : clazzes) { evictClass(clazz); } } public void evictClass(Class<? extends Entity> clazz) { SessionFactory sessionFactory = getSessionFactory(); Session session = SessionFactoryUtils.getSession(sessionFactory, true); try { // Clear session cache e.g. first level cache session.clear(); // Evict second-level cache sessionFactory.evict(clazz); } catch (HibernateException e) { String errorMessage = "Can't evict Class='" + clazz.getName() + "'."; logger.error(errorMessage, e); throw new RuntimeException(errorMessage, e); } } }