Java tutorial
/** * Copyright 2008 - 2011 Simcore.org. * * 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 com.project.framework.dao; import java.io.Serializable; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.hibernate.Criteria; import org.hibernate.Hibernate; import org.hibernate.ObjectNotFoundException; import org.hibernate.Query; import org.hibernate.SQLQuery; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.criterion.CriteriaSpecification; import org.hibernate.criterion.Criterion; import org.hibernate.criterion.Order; import org.hibernate.criterion.Restrictions; import org.hibernate.metadata.ClassMetadata; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.Assert; import com.project.framework.util.ReflectionUtils; /** * ?HibernateAPIDAO. * * ?Service,?DAO?. * ?Spring2.5Petlinc?,?HibernateTemplate,HibernateAPI. * * @param <T> DAO? * @param <ID> * <p> * @author ray */ @SuppressWarnings("unchecked") class GenericDao<T, ID extends Serializable> { protected Logger logger = LoggerFactory.getLogger(getClass()); @Resource protected SessionFactory sessionFactory; protected Class<T> entityClass; /** * Dao?. * ??Class.<p> * eg.<p> * <code>public class UserDao extends GenericDao<User, Long>{...}</code> */ public GenericDao() { this.entityClass = ReflectionUtils.getSuperClassGenricType(getClass()); System.out.println(entityClass.getName()); } /** * ?Dao, ServiceGenericDao. * Class.<p> * eg.<p> * <code>GenericDao<User, Long> userDao = new GenericDao<User, Long>(sessionFactory, User.class){...}</code> * * @param sessionFactory Hibernate Session * @param entityClass */ public GenericDao(final SessionFactory sessionFactory, final Class<T> entityClass) { this.sessionFactory = sessionFactory; this.entityClass = entityClass; } /** * ?sessionFactory. * * @return SessionFactory Hibernate Session */ public SessionFactory getSessionFactory() { return sessionFactory; } /** * @AutowiredSessionFactory, SesionFactoryOverride. * * @param sessionFactory Hibernate Session */ public void setSessionFactory(final SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } /** * ??Session. * * @return Session */ public Session getSession() { return sessionFactory.getCurrentSession(); } /** * ?. * * @param entity ?? */ public void save(final T entity) { Assert.notNull(entity, "entity Can not NULL"); getSession().saveOrUpdate(entity); logger.debug("Save {}: {}", entityClass.getSimpleName(), entity); } /** * ?. * * @param entity ?? */ public void update(final T entity) { Assert.notNull(entity, "entity Can not NULL"); getSession().update(entity); logger.debug("Save {}: {}", entityClass.getSimpleName(), entity); } /** * ? * * @param entitys ?? * @param flushSize ORM????? */ public void save(final List<T> entitys, int flushSize) { Assert.notNull(entitys, "entitys Can not NULL"); Assert.notEmpty(entitys, "entitys Can not EMPTY"); Session session = getSession(); int count = 1; for (T entity : entitys) { session.saveOrUpdate(entity); if (count++ % flushSize == 0) { session.flush(); session.clear(); } } logger.debug("batch save {}, number of rows affected: {}", entityClass.getSimpleName(), count - 1); } /** * . * * @param entity session?idtransient. */ public void delete(final T entity) { Assert.notNull(entity, "entity Can not NULL"); getSession().delete(entity); logger.debug("delete {}: {}", entityClass.getSimpleName(), entity); } /** * ? * * @param entitys * @param flushSize ORM????? */ public void delete(final List<T> entitys, int flushSize) { Assert.notNull(entitys, "entity Can not NULL"); Assert.notEmpty(entitys, "entitys Can not EMPTY"); Session session = getSession(); int count = 1; for (T entity : entitys) { session.delete(entity); if (count++ % flushSize == 0) { session.flush(); session.clear(); } } logger.debug("batch delete {}, number of rows affected: {}", entityClass.getSimpleName(), count - 1); } /** * id. * * @param id id */ public void deleteById(final ID id) { Assert.notNull(id, "entity Can not NULL"); getSession().delete(findById(id)); logger.debug("delete {},id is {}", entityClass.getSimpleName(), id); } /** * id? * * @param ids id */ public void deleteById(final List<ID> ids) { Assert.notNull(ids, "ids Can not NULL"); final String queryString = "delete from " + entityClass.getSimpleName() + " as model where model." + getIdName() + " in(:ids)"; Query query = createQuery(queryString); query.setParameterList("ids", ids); int result = query.executeUpdate(); logger.debug("batch delete {}, number of rows affected: {}", entityClass.getSimpleName(), result); } /** * id?. * * @param id ?id * @return T id,id?null. */ public T findById(final ID id) { Assert.notNull(id, "id Can not NULL"); T t = (T) getSession().load(entityClass, id); try { initEntity(t); } catch (ObjectNotFoundException e) { return null; } return t; } /** * ?ID * @param id * @return */ public T getEntity(final ID id) { try { T t = (T) getSession().get(entityClass, id); return t; } catch (Exception e) { return null; } } /** * ?. * * @return */ public List<T> findAll() { return executeQuery(); } /** * ?,??. * * @param orderBy ? * @param isAsc ??? * @return ? */ public List<T> findAll(final String orderBy, boolean isAsc) { Criteria criteria = createCriteria(); if (isAsc) { criteria.addOrder(Order.asc(orderBy)); } else { criteria.addOrder(Order.desc(orderBy)); } return criteria.list(); } /** * ,??. * * @param propertyName ?? * @param value ? * @return ? */ public List<T> findBy(final String propertyName, final Object value) { Assert.hasText(propertyName, "propertyName Can not NULL"); Criterion criterion = Restrictions.eq(propertyName, value); return executeQuery(criterion); } /** * ,??,??. * * @param propertyName ?? * @param value ? * @param orderBy ? * @param isAsc ??? * @return ?? */ public List<T> findBy(final String propertyName, final Object value, final String orderBy, boolean isAsc) { Assert.hasText(propertyName, "propertyName Can not NULL"); Criterion criterion = Restrictions.eq(propertyName, value); Criteria criteria = createCriteria(criterion); if (isAsc) { criteria.addOrder(Order.asc(orderBy)); } else { criteria.addOrder(Order.desc(orderBy)); } return criteria.list(); } /** * ,??. * * @param propertyName ?? * @param value ? * @return ? */ public T findUniqueBy(final String propertyName, final Object value) { Assert.hasText(propertyName, "propertyName Can not NULL"); Criterion criterion = Restrictions.eq(propertyName, value); return (T) createCriteria(criterion).uniqueResult(); } /** * ?. * * @param <X> ? * @param queryString ? * @param values ????,?. * @return */ public <X> List<X> executeQuery(final String queryString, final Object... values) { Assert.hasText(queryString, "queryString Can not NULL"); return createQuery(queryString, values).list(); } /** * ?. * * @param <X> ? * @param queryString ? * @param values ???,??. * @return */ public <X> List<X> executeQuery(final String queryString, final Map<String, ?> values) { Assert.hasText(queryString, "queryString Can not NULL"); return createQuery(queryString, values).list(); } /** * Criteria. * * @param criterions ???Criterion. * @return */ public List<T> executeQuery(final Criterion... criterions) { return createCriteria(criterions).list(); } /** * Criteria,? * @param orderBy ? * @param isAsc ??? * @param criterions ???Criterion. * @return */ public List<T> executeQueryWithOrder(final String orderBy, boolean isAsc, final Criterion... criterions) { Criteria criteria = createCriteria(criterions); if (isAsc) { criteria.addOrder(Order.asc(orderBy)); } else { criteria.addOrder(Order.desc(orderBy)); } return criteria.list(); } /** * ?. * * @param <X> ? * @param queryString ? * @param values ????,?. * @return */ public <X> X executeUniqueQuery(final String queryString, final Object... values) { Assert.hasText(queryString, "queryString Can not NULL"); return (X) createQuery(queryString, values).uniqueResult(); } /** * ?. * * @param <X> ? * @param queryString ? * @param values ???,??. * @return */ public <X> X executeUniqueQuery(final String queryString, final Map<String, ?> values) { Assert.hasText(queryString, "queryString Can not NULL"); return (X) createQuery(queryString, values).uniqueResult(); } /** * Criteria. * * @param criterions ???Criterion. * @return */ public T executeUniqueQuery(final Criterion... criterions) { return (T) createCriteria(criterions).uniqueResult(); } /** * ?/?. * * @param queryString ?? * @param values ?? * @return */ public int executeUpdate(final String queryString, final Object... values) { Assert.hasText(queryString, "queryString Can not NULL"); return createQuery(queryString, values).executeUpdate(); } /** * ?/?. * * @param queryString ?? * @param values ?? * @return . */ public int executeUpdate(final String queryString, final Map<String, ?> values) { Assert.hasText(queryString, "queryString Can not NULL"); return createQuery(queryString, values).executeUpdate(); } /** * ?/?. * * @param nativeQueryString ?? * @param values ?? * @return */ public int executeNativeUpdate(final String nativeQueryString, final Object... values) { Assert.hasText(nativeQueryString, "nativeQueryString Can not NULL"); return createNativeQuery(nativeQueryString, values).executeUpdate(); } /** * ??/?. * * @param nativeQueryString ?? * @param values ?? * @return */ public int executeNativeUpdate(final String nativeQueryString, final Map<String, ?> values) { Assert.hasText(nativeQueryString, "nativeQueryString Can not NULL"); return createNativeQuery(nativeQueryString, values).executeUpdate(); } /** * ???Query. * * ?find()T,?T. * * @param values ????,?. */ public Query createQuery(final String queryString, final Object... values) { Assert.hasText(queryString, "queryString Can not NULL"); Query query = getSession().createQuery(queryString); if (values != null) { for (int i = 0; i < values.length; i++) { query.setParameter(i, values[i]); } } return query; } /** * ?SQL??SQLQuery * * @param nativeQueryString SQL? * @param values ????,? */ public SQLQuery createNativeQuery(final String nativeQueryString, final Object... values) { Assert.hasText(nativeQueryString, "nativeQueryString Can not NULL"); SQLQuery query = getSession().createSQLQuery(nativeQueryString); if (values != null) { for (int i = 0; i < values.length; i++) { query.setParameter(i, values[i]); } } return query; } /** * ???Query. * * @param values ???,??. */ public Query createQuery(final String queryString, final Map<String, ?> values) { Assert.hasText(queryString, "queryString Can not NULL"); Query query = getSession().createQuery(queryString); if (values != null) { query.setProperties(values); } return query; } /** * ?SQL??SQLQuery * * @param values ???,??. */ public SQLQuery createNativeQuery(final String nativeQueryString, final Map<String, ?> values) { Assert.hasText(nativeQueryString, "nativeQueryString Can not NULL"); SQLQuery query = getSession().createSQLQuery(nativeQueryString); if (values != null) { query.setProperties(values); } return query; } /** * ?Criterion?Criteria. * * ?find()T,?T. * * @param criterions ???Criterion. */ public Criteria createCriteria(final Criterion... criterions) { Criteria criteria = getSession().createCriteria(entityClass); for (Criterion c : criterions) { criteria.add(c); } return criteria; } /** * ?. * load()Proxy, View???. * ??entity,????. * ??,?,: * Hibernate.initialize(user.getRoles())?User??. * Hibernate.initialize(user.getDescription())?UserDescription. */ public void initEntity(T entity) { Hibernate.initialize(entity); } /** * @see #initEntity(Object) */ public void initEntity(List<T> entityList) { for (T entity : entityList) { Hibernate.initialize(entity); } } /** * Flush?Session. */ public void flush() { getSession().flush(); } /** * Querydistinct transformer. */ public Query distinct(Query query) { query.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY); return query; } /** * Criteriadistinct transformer. */ public Criteria distinct(Criteria criteria) { criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY); return criteria; } /** * ???. */ public String getIdName() { ClassMetadata meta = getSessionFactory().getClassMetadata(entityClass); return meta.getIdentifierPropertyName(); } }