Java tutorial
/* * Copyright 2010-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.reusables.access; import static java.lang.String.format; import java.io.Serializable; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.util.List; import org.apache.commons.lang.Validate; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.criterion.DetachedCriteria; import org.hibernate.criterion.Order; import org.springframework.beans.factory.InitializingBean; import org.springframework.util.ClassUtils; import org.springframework.util.ReflectionUtils; /** * Abstract implementation, using {@link SessionFactory}, for the {@link GeneralRepository} interface * offering a number a standard methods generic for most repostories. * @author marcel * @param <T> Entity type for this repository. * @since 1.1 **/ public abstract class AbstractHibernateRepository<T> implements GeneralRepository<T>, InitializingBean { private final Class<T> entityClass; private SessionFactory sessionFactory; /** * Spring's way of handling multiple Hibernate versions: * * A Method handle for the <code>SessionFactory.getCurrentSession()</code> method. * The return value differs between Hibernate 3.x and 4.x; for cross-compilation purposes, * we have to use reflection here as long as we keep supporting Hibernate 3.x. */ private static final Method getCurrentSessionMethod = ClassUtils.getMethod(SessionFactory.class, "getCurrentSession"); /** * Constructor. */ protected AbstractHibernateRepository() { this(null); } /** * Constructor. * * @param sessionFactory The session factory to use. * @since 1.2.1 */ @SuppressWarnings("unchecked") protected AbstractHibernateRepository(final SessionFactory sessionFactory) { this.entityClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()) .getActualTypeArguments()[0]; this.sessionFactory = sessionFactory; } /** * @param sessionFactory The Hibernate session factory to use. */ public void setSessionFactory(final SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } @Override public void afterPropertiesSet() throws Exception { Validate.notNull(this.sessionFactory, "No sessionFactory supplied."); } @Override public T getById(final Serializable id) { final T entity = (T) getSession().get(this.entityClass, id); Validate.notNull(entity, "No entity found with id: " + id); return entity; } @Override public List<T> findAll(final String orderByPropertyName) // TODO cachable boolean { final DetachedCriteria crit = DetachedCriteria.forClass(this.entityClass); if (orderByPropertyName != null) { crit.addOrder(Order.asc(orderByPropertyName)); } return findByCriteria(crit); } @Override public void save(final T entity) { getSession().save(entity); } @Override public void delete(final T entity) { getSession().delete(entity); } @Override public int deleteById(final Serializable id) { return deleteById(id, DEFAULT_ID); } @Override public int deleteById(final Serializable id, final String idPropertyName) { final String hql = format("delete %s where %s = :entityId", this.entityClass.getName(), idPropertyName); final Query query = getSession().createQuery(hql); query.setParameter("entityId", id); return query.executeUpdate(); } /** * @param criteria The criteria to use for the query. * @return The result found. */ protected List<T> findByCriteria(final DetachedCriteria criteria) // TODO support first, max results, TODO different entity class. TODO cachable boolean { return criteria.getExecutableCriteria(getSession()).list(); } /** * @return The currect session. * @since 1.2.0 */ protected Session getSession() { return (Session) ReflectionUtils.invokeMethod(getCurrentSessionMethod, this.sessionFactory); } }