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 calvinxiu $ */ package gov.abrs.etms.dao.util; import gov.abrs.etms.common.util.Carrier; import java.util.Collection; import java.util.List; import java.util.Map; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.hibernate.Criteria; import org.hibernate.Hibernate; import org.hibernate.Query; 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.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.Assert; @Repository @SuppressWarnings("unchecked") public class ExecuteDAO { protected Logger logger = Logger.getLogger(getClass()); protected SessionFactory sessionFactory; public ExecuteDAO() { } /** * ??Session. */ public Session getSession() { return sessionFactory.getCurrentSession(); } /** * ?. */ public void save(final Class entityClass, final Object entity) { Assert.notNull(entity, "entity?"); getSession().saveOrUpdate(entity); logger.debug("save entity: " + entityClass.getSimpleName()); } /** * . * * @param entity * session?idtransient. */ public void delete(final Class entityClass, final Object entity) { Assert.notNull(entity, "entity?"); getSession().delete(entity); logger.debug("delete entity: " + entityClass.getSimpleName()); } /** * id. */ public void delete(final Class entityClass, final Long id) { Assert.notNull(id, "id?"); delete(entityClass, get(entityClass, id)); logger.debug("delete entity " + entityClass.getSimpleName() + "," + "id is " + id); } /** * id?. */ @Transactional(propagation = Propagation.REQUIRED, readOnly = true) public <X> X get(final Class entityClass, final Long id) { Assert.notNull(id, "id?"); return (X) getSession().get(entityClass, id); } /** * id?(?). */ public <X> X getWithStatelessSession(final Class entityClass, final Long id) { Assert.notNull(id, "id?"); String hql = "from " + entityClass.getName() + " where id =:id"; Query query = this.getSessionFactory().openStatelessSession().createQuery(hql); query.setLong("id", id); List<X> list = query.list(); if (list == null || list.size() == 0) { return null; } else { return list.get(0); } } /** * id?. */ public List get(final Class entityClass, final Collection<Long> ids) { return find(entityClass, Restrictions.in(getIdName(entityClass), ids)); } /** * ?. */ public List getAll(final Class entityClass) { String hql = "from " + entityClass.getSimpleName(); Query query = this.getSession().createQuery(hql); return query.list(); } /** * ?, ??. */ public List getAll(final Class entityClass, String orderByProperty, boolean isAsc) { Criteria c = createCriteria(entityClass); if (isAsc) { c.addOrder(Order.asc(orderByProperty)); } else { c.addOrder(Order.desc(orderByProperty)); } return c.list(); } /** * , ??. */ public List findBy(final Class entityClass, final String propertyName, final Object value) { Assert.hasText(propertyName, "propertyName?"); Criterion criterion = Restrictions.eq(propertyName, value); return find(entityClass, criterion); } /** * , ??. */ public Object findUniqueBy(final Class entityClass, final String propertyName, final Object value) { Assert.hasText(propertyName, "propertyName?"); Criterion criterion = Restrictions.eq(propertyName, value); return createCriteria(entityClass, criterion).uniqueResult(); } /** * SQL. * * @param sql * ???Sql. */ public Object findObjectUnique(String sql) { return this.getSession().createSQLQuery(sql).uniqueResult(); } /** * 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, 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(); } /** * ?HQL?Query. find()???. * * @param values * ????,?. */ public Query createQuery(final String queryString, final Object... values) { Assert.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; } /** * ?HQL?Query. find()???. * * @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; } /** * Criteria. * * @param criterions * ???Criterion. */ public List find(final Class entityClass, final Criterion... criterions) { return createCriteria(entityClass, criterions).list(); } /** * Criteria. * * @param criterions * ???Criterion. */ public Object findUnique(final Class entityClass, final Criterion... criterions) { return createCriteria(entityClass, criterions).uniqueResult(); } /** * ?Criterion?Criteria. find()???. * * @param criterions * ???Criterion. */ public Criteria createCriteria(final Class entityClass, final Criterion... criterions) { Criteria criteria = getSession().createCriteria(entityClass); for (Criterion c : criterions) { criteria.add(c); } return criteria; } /** * ?. 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(); } /** * Querydistinct transformer. ?HQL??, ?distinct?. */ public Query distinct(Query query) { query.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY); return query; } /** * Criteriadistinct transformer. ?HQL??, ?distinct?. */ public Criteria distinct(Criteria criteria) { criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY); return criteria; } /** * ???. */ public String getIdName(final Class entityClass) { ClassMetadata meta = getSessionFactory().getClassMetadata(entityClass); return meta.getIdentifierPropertyName(); } /** * ??. * * ,(value)?(orgValue)?. */ public boolean isPropertyUnique(final Class entityClass, final String propertyName, final Object newValue, final Object oldValue) { if (newValue == null || newValue.equals(oldValue)) { return true; } Object object = findUniqueBy(entityClass, propertyName, newValue); return (object == null); } //-- --// /** * ?. */ public void find(final Class entityClass, final Carrier carrier) { String hql = "from " + entityClass.getSimpleName(); hql = setPageParameterToHql(hql, carrier); Query query = this.getSession().createQuery(hql); if (carrier.isAutoCount()) { long totalCount = countHqlResult(hql); carrier.setTotalSize(totalCount); } setPageParameterToQuery(query, carrier); List result = query.list(); carrier.setResult(result); } public <X> List<X> getByNameLike(final Class entityClass, final String nameLike) { String hql = "from " + entityClass.getSimpleName() + " c where c.name like ?"; return this.find(hql, "%" + nameLike + "%"); } //??? public <X> X getByName(final Class entityClass, final String name) { String hql = "from " + entityClass.getSimpleName() + " c where c.name = ?"; return (X) this.findUnique(hql, name); } /** * */ public void delete(final Class entityClass, final Carrier carrier) throws Exception { JSONArray array = JSONArray.fromObject(carrier.getDelIds()); for (Object object : array) { Long delId = ((JSONObject) object).getLong("id"); delete(entityClass, delId); } } /** * HQL. * * @param carrier ?. * @param hql hql?. * @param values ????,?. * * @return , ??. */ public Carrier find(final Carrier carrier, String hql, final Object... values) { Assert.notNull(carrier, "carrier?"); hql = setPageParameterToHql(hql, carrier); Query q = createQuery(hql, values); if (carrier.isAutoCount()) { long totalCount = countHqlResult(hql, values); carrier.setTotalSize(totalCount); } setPageParameterToQuery(q, carrier); List result = q.list(); carrier.setResult(result); return carrier; } /** * HQL. * * @param carrier ?. ???orderBy?. * @param hql hql?. * @param values ???,??. * * @return , ??. */ public void find(final Carrier carrier, String hql, final Map<String, ?> values) { Assert.notNull(carrier, "carrier?"); try { hql = setPageParameterToHql(hql, carrier); Query q = createQuery(hql, values); if (carrier.isAutoCount()) { long totalCount = countHqlResult(hql, values); carrier.setTotalSize(totalCount); } setPageParameterToQuery(q, carrier); List result = q.list(); carrier.setResult(result); } catch (Exception e) { e.printStackTrace(); } } /** * ?Query,. */ protected Query setPageParameterToQuery(final Query q, final Carrier carrier) { Assert.isTrue(carrier.getPageSize() > 0, "Page Size must larger than zero"); //hibernatefirstResult??0 q.setFirstResult(carrier.getFirstResult()); q.setMaxResults(carrier.getPageSize()); return q; } /** * ?hql,. */ private String setPageParameterToHql(String hql, final Carrier carrier) { String sidx = carrier.getSidx(); String sord = carrier.getSord(); String filters = carrier.getFilters(); if (filters != null && !filters.equals("")) { if (hql.lastIndexOf("where") > 0) { hql += " and " + filters; } else { hql += " where " + filters; } } if (sidx != null && !sidx.equals("")) { if (sidx.indexOf("_") == -1) { hql += " order by " + sidx; } else { hql += " order by " + sidx.replace("_", "."); } if (carrier.getSord() != null && !carrier.getSord().equals("")) { hql += " " + sord; } else { hql += " asc"; } } return hql; } /** * countHql. * * ???hql?,??hql?count?. */ protected long countHqlResult(final String hql) { String countHql = prepareCountHql(hql); try { Long count = findUnique(countHql); return count; } catch (Exception e) { throw new RuntimeException("hql can't be auto count, hql is:" + countHql, e); } } /** * countHql. * * ???hql?,??hql?count?. */ protected long countHqlResult(final String hql, final Object... values) { String countHql = prepareCountHql(hql); try { Long count = findUnique(countHql, values); return count; } catch (Exception e) { throw new RuntimeException("hql can't be auto count, hql is:" + countHql, e); } } /** * countHql. * * ???hql?,??hql?count?. */ protected long countHqlResult(final String hql, final Map<String, ?> values) { String countHql = prepareCountHql(hql); try { Long count = findUnique(countHql, values); return count; } catch (Exception e) { throw new RuntimeException("hql can't be auto count, hql is:" + countHql, e); } } private String prepareCountHql(String orgHql) { String fromHql = orgHql; //select??order by???count,?. fromHql = "from " + StringUtils.substringAfter(fromHql, "from"); fromHql = StringUtils.substringBefore(fromHql, "order by"); String countHql = "select count(*) " + fromHql; return countHql; } public int countRows(Class entityClass) { String countHql = "select count(*) from " + entityClass.getSimpleName(); try { Long count = findUnique(countHql); return count.intValue(); } catch (Exception e) { throw new RuntimeException("hql can't be auto count, hql is:" + countHql, e); } } /** * ?sessionFactory. */ public SessionFactory getSessionFactory() { return sessionFactory; } /** * @AutowiredSessionFactory, SesionFactory??. */ @Autowired public void setSessionFactory(final SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } }