Java tutorial
/** * Copyright (c) 2005-2010 springside.org.cn * * Licensed under the Apache License, Version 2.0 (the "License"); * * $Id: SimpleHibernateDao.java 1205 2010-09-09 15:12:17Z xiaoxiu $ */ package com.macrosoft.core.orm.hibernate; import java.io.Serializable; import java.util.Enumeration; import java.util.Hashtable; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.hibernate.Criteria; import org.hibernate.Hibernate; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; 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.beans.factory.annotation.Autowired; import org.springframework.util.Assert; import com.macrosoft.common.reflection.ReflectionUtils; /** * ?HibernateAPIDAO. * * ?Service, ?DAO?, ?. * ?Spring2.5Petlinc?, ?HibernateTemplate, HibernateAPI. * * @param <T> DAO? * @param <PK> * * @author xiao */ @SuppressWarnings("unchecked") public class SimpleHibernateDao<T, PK extends Serializable> { protected Logger logger = LoggerFactory.getLogger(getClass()); protected SessionFactory sessionFactory; protected Class<T> entityClass; /** * Dao?. * ??Class. * eg. * public class UserDao extends SimpleHibernateDao<User, Long> */ public SimpleHibernateDao() { this.entityClass = ReflectionUtils.getClassGenricType(getClass()); } /** * ?Dao, ServiceSimpleHibernateDao. * Class. * eg. * SimpleHibernateDao<User, Long> userDao = new SimpleHibernateDao<User, Long>(sessionFactory, User.class); */ public SimpleHibernateDao(final SessionFactory sessionFactory, final Class<T> entityClass) { this.sessionFactory = sessionFactory; this.entityClass = entityClass; } /** * ?sessionFactory. */ public SessionFactory getSessionFactory() { return sessionFactory; } /** * @AutowiredSessionFactory,SesionFactoryOverride. */ @Autowired public void setSessionFactory(final SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } /** * ??Session. */ public Session getSession() { return sessionFactory.getCurrentSession(); } /** * ?. */ private void save1(final T entity) { Assert.notNull(entity, "entity?"); Session session = getSessionFactory().openSession(); Transaction tran = null; try { if (session != null) { tran = session.beginTransaction(); tran.begin(); session.saveOrUpdate(entity); tran.commit(); } } catch (Exception ex) { tran.rollback(); } finally { if (session != null) { session.close(); } } logger.debug("save entity: {}", entity); } /** * ?. */ public void save(final T entity) { Assert.notNull(entity, "entity?"); getSession().saveOrUpdate(entity); logger.debug("save entity: {}", entity); } /** * . * * @param entity session?idtransient. */ public void delete(final T entity) { Assert.notNull(entity, "entity?"); getSession().delete(entity); logger.debug("delete entity: {}", entity); } /** * . * * @param entity session?idtransient. */ private void delete1(final T entity) { Assert.notNull(entity, "entity?"); Session session = getSessionFactory().openSession(); Transaction tran = null; try { if (session != null) { tran = session.beginTransaction(); tran.begin(); session.delete(entity); tran.commit(); } } catch (Exception ex) { tran.rollback(); } finally { if (session != null) { session.close(); } } logger.debug("delete entity: {}", entity); } /** * id. */ public void delete(final PK id) { Assert.notNull(id, "id?"); delete(get(id)); logger.debug("delete entity {},id is {}", entityClass.getSimpleName(), id); } /** * id?. */ public T get(final PK id) { Assert.notNull(id, "id?"); return (T) getSession().load(entityClass, id); } /** * ?. */ public List<T> getAll() { return find(); } /** * ?,??. */ public List<T> getAll(String orderBy, boolean isAsc) { Criteria c = createCriteria(); if (isAsc) { c.addOrder(Order.asc(orderBy)); } else { c.addOrder(Order.desc(orderBy)); } return c.list(); } /** * ,??. */ public List<T> findBy(final String propertyName, final Object value) { Assert.hasText(propertyName, "propertyName?"); Criterion criterion = Restrictions.eq(propertyName, value); return find(criterion); } /** * ,??. */ public T findUniqueBy(final String propertyName, final Object value) { Assert.hasText(propertyName, "propertyName?"); if (value == null) { return null; } if (value instanceof String) { if (StringUtils.isEmpty((String) value) == true) { return null; } } else { if (value instanceof Long) { Long temp = (Long) value; if (temp.intValue() <= 0) { return null; } } else { if (value instanceof Integer) { Integer temp = (Integer) value; if (temp.intValue() <= 0) { return null; } } } } Criterion criterion = Restrictions.eq(propertyName, value); return (T) createCriteria(criterion).uniqueResult(); } /** * id?. */ public List<T> findByIds(List<PK> ids) { return find(Restrictions.in(getIdName(), ids)); } /** * HQL. * * @param values ????,?. */ public <X> List<X> find(final String hql) { return createQuery(hql).list(); } /** * HQL. * * @param values ????,?. */ public <X> List<X> find(final String hql, final Object... values) { return createQuery(hql, values).list(); } /** * HQL. * * @param values ???,??. */ public <X> List<X> find(final String hql, final Map<String, ?> values) { return createQuery(hql, values).list(); } /** * HQL. * * @param values ????,?. */ public <X> X findUnique(final String hql) { return (X) createQuery(hql).uniqueResult(); } /** * 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?/?. */ public int batchExecute(final String hql, final Object... values) { return createQuery(hql, values).executeUpdate(); } /** * HQL?/?. * @return . */ public int batchExecute(final String hql, final Map<String, ?> values) { return createQuery(hql, values).executeUpdate(); } /** * ?HQL?Query. * * ?find()T,?T. * */ public Query createQuery(final String queryString) { Assert.hasText(queryString, "queryString?"); Query query = getSession().createQuery(queryString); return query; } /** * ?HQL?Query. * * ?find()T,?T. * * @param values ????,?. */ public Query createQuery(final String queryString, final Object... values) { Assert.hasText(queryString, "queryString?"); Query query = getSession().createQuery(queryString); if (values != null && values.length > 0) { if (values[0] instanceof Hashtable) { Hashtable temp = (Hashtable) values[0]; query = setParamHash(query, temp); } else { if (values[0] instanceof List) { List temp = (List) values[0]; int size = temp.size(); for (int i = 0; i < size; i++) { Object param = temp.get(i); //query.setParameter(i,values[i]); if (param instanceof String) { String paramValue = (String) param; query.setString(i, paramValue); } else { if (param instanceof Integer) { Integer paramValue = (Integer) param; query.setInteger(i, paramValue.intValue()); } else { if (param instanceof Long) { Long paramValue = (Long) param; query.setLong(i, paramValue.longValue()); } else { if (param instanceof Double) { Double paramValue = (Double) param; query.setDouble(i, paramValue.doubleValue()); } else { if (param instanceof Float) { Float paramValue = (Float) param; query.setFloat(i, paramValue.floatValue()); } } } } } } } else { for (int i = 0; i < values.length; i++) { query.setParameter(i, values[i]); } } } } return query; } /** * ?HQL?Query. * * @param values ???,??. */ public Query createQuery(final String queryString, final Map<String, ?> values) { Assert.hasText(queryString, "queryString?"); Query query = getSession().createQuery(queryString); if (values != null) { query.setProperties(values); } return query; } /** * * @param query * @param values * @return */ private Query setParamHash(Query query, Hashtable<String, ?> values) { if (values != null) { //query.setProperties(values); Enumeration parameterNames = values.keys(); while (parameterNames.hasMoreElements() == true) { String pName = (String) parameterNames.nextElement(); Object param = values.get(pName); if (param instanceof String) { String paramValue = (String) param; query.setString(pName, paramValue); } else { if (param instanceof Integer) { Integer paramValue = (Integer) param; query.setInteger(pName, paramValue.intValue()); } else { if (param instanceof Double) { Double paramValue = (Double) param; query.setDouble(pName, paramValue.doubleValue()); } } } } } return query; } /** * 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(); } /** * ?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); } } /** * 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(); } }