Java tutorial
package com.lighting.platform.base.dao; /** * Copyright (c) 2005-20101 springside.org.cn * * Licensed under the Apache License, Version 2.0 (the "License"); * * $Id: SimpleHibernateDao.java 1486 2011-02-12 15:50:51Z calvinxiu $ */ import java.io.Serializable; import java.util.Collection; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hibernate.Criteria; import org.hibernate.Hibernate; import org.hibernate.LockMode; import org.hibernate.LockOptions; import org.hibernate.Query; import org.hibernate.ReplicationMode; 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.hibernate.transform.Transformers; import org.springframework.beans.factory.annotation.Autowired; import com.lighting.platform.base.utils.AssertUtils; import com.lighting.platform.base.utils.ReflectionUtils; /** * ?HibernateAPIDAO. * * ?Spring2.5Petlinc?, ?HibernateTemplate, HibernateAPI. * * @param <T> DAO? * @param <ID> * * @author changhao */ @SuppressWarnings({ "rawtypes", "unchecked" }) public class SimpleHibernateDao<T, ID extends Serializable> { protected Log logger = LogFactory.getLog(getClass()); protected SessionFactory sessionFactory; protected Class<T> entityClass; /** * ??Class. * eg. * public class UserDao extends SimpleHibernateDao<User, Long> */ public SimpleHibernateDao() { this.entityClass = ReflectionUtils.getSuperClassGenricType(getClass()); } public SimpleHibernateDao(Class<T> entityClass) { this.entityClass = entityClass; } /** * ?sessionFactory. */ public SessionFactory getSessionFactory() { return sessionFactory; } /** * ?ID?,ID,? * ? * @param t */ public void insertDIYID(final T t) { getSession().replicate(t, ReplicationMode.EXCEPTION); } /** * @AutowiredSessionFactory, SesionFactory??. */ @Autowired public void setSessionFactory(final SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } /** * ??Session. */ public Session getSession() { return sessionFactory.openSession(); } /** * ??, select ... for update * ?, ???. */ public void pessimisticLock(T entity) { LockOptions option = new LockOptions(LockMode.PESSIMISTIC_WRITE); getSession().buildLockRequest(option).lock(entity); } /** * ??? (very useful) * @param action */ /*public void doAfterTransactionCompletion(final Action action) { SessionImpl sessionImpl = (SessionImpl) getSession(); sessionImpl.getActionQueue().registerProcess(new AfterTransactionCompletionProcess() { @Override public void doAfterTransactionCompletion(boolean success, SessionImplementor session) { try { action.doAction(success); } catch (Exception e) { logger.error("Error in doAfterTransactionCompletion action", e); } } }); }*/ /** * ?. */ public T save(final T entity) { AssertUtils.notNull(entity, "entity?"); check(entity); getSession().saveOrUpdate(entity); return entity; } public void save(final List<T> entities) { for (int i = 0; i < entities.size(); i++) { save(entities.get(i)); } } public T merge(final T entity) { AssertUtils.notNull(entity, "entity?"); check(entity); return (T) getSession().merge(entity); } /** * ? * @param entity */ protected void check(final T entity) { } /** * . * * @param entity session?idtransient. */ public void delete(final T entity) { AssertUtils.notNull(entity, "entity?"); getSession().delete(entity); } public void delete(List<T> entitys) { if (entitys != null && !entitys.isEmpty()) { for (T entity : entitys) { delete(entity); } } } /** * id. */ public void delete(final ID id) { AssertUtils.notNull(id, "id?"); delete(get(id)); } /** * ?load, get */ public T get(final ID id) { AssertUtils.notNull(id, "id?"); return (T) getSession().get(entityClass, id); } /** * id?. */ public List<T> get(final Collection<ID> ids) { return find(Restrictions.in(getIdName(), ids)); } /** * ?. */ public List<T> getAll() { return find(); } /** * ?, ??. */ public List<T> getAll(String orderByProperty, boolean isAsc) { Criteria c = createCriteria(); if (isAsc) { c.addOrder(Order.asc(orderByProperty)); } else { c.addOrder(Order.desc(orderByProperty)); } return c.list(); } /** * , ??. */ public List<T> findBy(final String propertyName, final Object value) { AssertUtils.hasText(propertyName, "propertyName?"); Criterion criterion = Restrictions.eq(propertyName, value); return find(criterion); } /** * , ??. */ public T findUniqueBy(final String propertyName, final Object value) { AssertUtils.hasText(propertyName, "propertyName?"); Criterion criterion = Restrictions.eq(propertyName, value); return (T) createCriteria(criterion).uniqueResult(); } /** * HQL. * * @param values ????,?. */ public <X> List<X> find(final String hql, final Object... values) { return createQuery(hql, values).list(); } /** * HQL. * @param <X> * @param hql * @param clazz ? * @param values * @return */ public <X> List<X> find(final String hql, Class<X> clazz, final Object... values) { return createQuery(hql, values).setResultTransformer(Transformers.aliasToBean(clazz)).list(); } /** * HQL. * * @param values ???,??. */ public <X> List<X> find(final String hql, final Map<String, ?> values) { return createQuery(hql, values).list(); } public <X> List<X> find(final SqlEso eso) { return createQuery(eso.getSql(), eso.getParam()).list(); } public <X> List<X> find(final SqlEso eso, Class<X> clazz) { return find(eso.getSql(), eso.getParam(), clazz); } /** * HQL. * * @param values ????,?. */ public <X> X findUnique(final String hql, final Object... values) { return (X) createQuery(hql, values).uniqueResult(); } /** * HQL. * * @param values ???,??. */ public <X> X findUnique(final String hql, final Map<String, ?> values) { return (X) createQuery(hql, values).uniqueResult(); } /** * HQL?/?. * * @param values ????,?. * @return . */ public int batchExecute(final String hql, final Object... values) { return createQuery(hql, values).executeUpdate(); } /** * HQL?/?. * * @param values ???,??. * @return . */ public int batchExecute(final String hql, final Map<String, ?> values) { return createQuery(hql, values).executeUpdate(); } /** * Criteria. * * @param criterions ???Criterion. */ public List<T> find(final Criterion... criterions) { return createCriteria(criterions).list(); } /** * Criteria. * * @param criterions ???Criterion. */ public T findUnique(final Criterion... criterions) { return (T) createCriteria(criterions).uniqueResult(); } /** * ?. * load()Proxy, View???. * entity, ??entity,????. * ??,: * Hibernate.initialize(user.getRoles())?User??. * Hibernate.initialize(user.getDescription())?UserDescription. */ public void initProxyObject(Object proxy) { Hibernate.initialize(proxy); } /** * Flush?Session. */ public void flush() { getSession().flush(); } /** * ?session? */ public void refresh(T obj) { getSession().refresh(obj); } /** * ???. */ public String getIdName() { ClassMetadata meta = getSessionFactory().getClassMetadata(entityClass); return meta.getIdentifierPropertyName(); } /** * ??. * * ,(value)?(orgValue)?. */ public boolean isPropertyUnique(final String propertyName, final Object newValue, final Object oldValue) { // ? ??? if (newValue == null || newValue.equals(oldValue)) { return true; } List list = findBy(propertyName, newValue); return list.isEmpty(); } public Number queryForNumber(final String hsql, Object... params) { Query query = this.createQuery(hsql, params); return (Number) query.uniqueResult(); } /** * ? * @param seqName ??? * @return */ public Number getNextSeqVal(String seqName) { AssertUtils.hasText(seqName, "????"); return (Number) this.getSession().createSQLQuery("select " + seqName + ".nextval from dual").uniqueResult(); } protected boolean cacheable() { return false; } /** * Criteriadistinct transformer. * ?HQL??, ?distinct?. */ public Criteria distinct(Criteria criteria) { criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY); return criteria.setCacheable(cacheable()); } /** * Querydistinct transformer. * ?HQL??, ?distinct?. */ public Query distinct(Query query) { query.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY); return query.setCacheable(cacheable()); } /** * ?Criterion?Criteria. * find()???. * * @param criterions ???Criterion. */ public Criteria createCriteria(final Criterion... criterions) { Criteria criteria = getSession().createCriteria(entityClass); for (Criterion c : criterions) { criteria.add(c); } return criteria.setCacheable(cacheable()); } /** * ?HQL?Query. * find()???. * * @param values ????,?. */ public Query createQuery(final String queryString, final Object... values) { AssertUtils.hasText(queryString, "queryString?"); Query query = getSession().createQuery(queryString); if (values != null) { for (int i = 0; i < values.length; i++) { query.setParameter(i, values[i]); } } return query.setCacheable(cacheable()); } /** * ?HQL?Query. * find()???. * * @param values ???,??. */ public Query createQuery(final String queryString, final Map<String, ?> values) { AssertUtils.hasText(queryString, "queryString?"); Query query = getSession().createQuery(queryString); if (values != null) { query.setProperties(values); } return query.setCacheable(cacheable()); } public Query createQuery(final SqlEso eso) { return createQuery(eso.getSql(), eso.getParam()); } }