Java tutorial
/** * @(#)HibernateDao.java 2009-12-8 * * Copyright 2000-2009 by RENWOYOU Corporation. * * All rights reserved. * * This software is the confidential and proprietary information of RENWOYOU Corporation ("Confidential Information"). You shall not disclose such Confidential Information and * shall use it only in accordance with the terms of the license agreement you entered into with RENWOYOU. * */ package cc.cnfc.core.orm.hibernate; import java.util.HashMap; import java.util.List; import java.util.Map; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataAccessException; import org.springframework.stereotype.Repository; import org.springframework.util.Assert; import cc.cnfc.core.exception.GenericException; import cc.cnfc.core.utils.StringUtil; /** * ?Hibernat DAO.?HibernatePage * * serviceBaseServiceDAO?? DAOSimpleHibernateDao * * @author fwgroup */ @Repository @SuppressWarnings({ "rawtypes", "unchecked" }) public final class HibernateDao { private final Logger logger = LoggerFactory.getLogger(getClass()); private SessionFactory sessionFactory; /** * ?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(); } /** * ?HQueryInfo(Hibernate???)?? * list?countHQueryInfo * * @param queryInfo * Hibernate??? * @return HQueryInfo ?list?count */ public HibernatePage query(final HibernatePage queryInfo) { if (queryInfo == null) return null; // ?? String className = queryInfo.getQueryClass().getName(); String hql = " from " + className; List propertyNamesLs = queryInfo.getPropertyNames(); String[] propertyNames = (String[]) propertyNamesLs.toArray(new String[propertyNamesLs.size()]); List operatorsLs = queryInfo.getOperators(); String[] operators = (String[]) operatorsLs.toArray(new String[operatorsLs.size()]); List valuesList = queryInfo.getValues(); Object[] values = valuesList == null || valuesList.size() == 0 ? null : valuesList.toArray(); int offset = queryInfo.getOffset(); int size = queryInfo.getPageSize(); boolean isTotalSize = queryInfo.isCountTotalSize(); String orderBy = queryInfo.getOrderBy(); String groupBy = queryInfo.getGroupBy(); String otherCause = queryInfo.getOtherHql(); // Object[] result = this.query(hql, propertyNames, operators, values, offset, size, isTotalSize, orderBy, groupBy, otherCause); // QueryInfo queryInfo.setQueryList((List) result[0]); queryInfo.setRecordCount(result[1] != null ? ((Integer) result[1]).intValue() : 0); // QueryInfo return queryInfo; } public Object[] query(final String hql, final String[] propertyNames, final String[] operators, final Object[] values, final int offset, final int size, final boolean isTotalSize, final String orderBy, final String groupBy, final String otherCause) { return this.query(hql, propertyNames, operators, values, offset, size, isTotalSize, orderBy, groupBy, otherCause, false); } /** * ??HQL?? * * 1?? a)?(MySQL,Oracle,SQL * Server2005)?limit n,m b)?(informix,Sybase 12.5.3,SQL * Server)?top n c)???? 2? * 3?order bygroup by,having Query q= session.createQuery( * "select new A(M.a,N.b) from M as M,N as N where M.id=N.id"); * * @param hql * HQL??Where???select???? select * a,b,(select c from table1) as d from table2 ... * 1)(select *)??from TUser * 2)select userName,password from TUser; * @param propertyNames * ??? * @param operators * ????=???null * ???=, >=, <=, <>, !=, like * @param values * ? * @param offset * 0??-1 * @param size * ??-1 * @param isTotalSize * ??true * @param orderBy * ?,??order byorderBy="a desc,b asc",??order by a * desc,b asc * @param groupBy * ,??group by groupBy="a desc,b asc",??group by a * desc,b asc * @param otherCause * where????(order by),(group by)??(having) * @param isCache * ?cache "group by name order by name desc" * @return Object[] List list = (List)Object[0] * int count = ((Integer)Object[1]).intValue; * @throws com.rwy.base.core.exception.GenericException * */ public Object[] query(final String hql, final String[] propertyNames, final String[] operators, final Object[] values, final int offset, final int size, final boolean isTotalSize, final String orderBy, final String groupBy, final String otherCause, final boolean isCache) throws DataAccessException { Assert.hasText(hql, "hql?"); Query query; String countSql; String fullSql; Integer count = 0; Map map = new HashMap(); String where = ""; if (propertyNames != null && propertyNames.length > 0 && values != null && values.length > 0) { if (propertyNames.length != values.length) { throw new GenericException(); } if (operators != null && propertyNames.length != operators.length) { logger.error(""); throw new GenericException(); } for (int i = 0; i <= propertyNames.length - 1; i++) { if ("".equals(where)) { where = " where "; } else { where += "and "; } if (operators != null && operators[i].equalsIgnoreCase("isnull")) { where += propertyNames[i] + " is null "; } else if (operators != null && operators[i].equalsIgnoreCase("isnotnull")) { where += propertyNames[i] + " is not null "; } else if (operators != null && operators[i].equalsIgnoreCase("isempty")) { where += propertyNames[i] + " = '' "; } else if (operators != null && operators[i].equalsIgnoreCase("isnotempty")) { where += propertyNames[i] + " <> '' "; } else if (operators != null && operators[i].equalsIgnoreCase("in")) { where += propertyNames[i] + " in "; } else { where += propertyNames[i] + (operators == null || operators[i] == null ? "=" : " " + operators[i]) + " ? "; } } fullSql = hql + where; fullSql += otherCause == null || otherCause.trim().equals("") ? "" : " " + otherCause; fullSql += groupBy == null || groupBy.trim().equals("") ? "" : " group by " + groupBy; fullSql += orderBy == null || orderBy.trim().equals("") ? "" : " order by " + orderBy; query = isCache ? this.createQuery(fullSql).setCacheable(true) : this.createQuery(fullSql); int paramIndex = 0; for (int i = 0; i <= values.length - 1; i++) { if (operators != null && operators[i].equalsIgnoreCase("isnull")) continue; if (operators != null && operators[i].equalsIgnoreCase("isnotnull")) continue; if (operators != null && operators[i].equalsIgnoreCase("isempty")) continue; if (operators != null && operators[i].equalsIgnoreCase("isnotempty")) continue; // IN? if (operators != null && operators[i].equalsIgnoreCase("in")) { values[i] = StringUtil.getInString(values[i]); } query.setParameter(paramIndex++, values[i]); } } else { if ("".equals(where) && hql.indexOf("where") == -1) { where = " where 1=1 "; } else if (!"".equals(where)) { where += " and "; } fullSql = hql + where; fullSql += otherCause == null || otherCause.trim().equals("") ? "" : " " + otherCause; fullSql += groupBy == null || groupBy.trim().equals("") ? "" : " group by " + groupBy; fullSql += orderBy == null || orderBy.trim().equals("") ? "" : " order by " + orderBy; query = this.createQuery(fullSql); } // ? if (isTotalSize) { // ???order by ??? countSql = hql + where; // modi by hongdj countSql += groupBy == null || groupBy.trim().equals("") ? "" : " group by " + groupBy; countSql += otherCause == null || otherCause.trim().equals("") ? "" : " " + otherCause; // ?hql?hql??select???? // select a,b,(select c from table1) as d from table2 ... countSql = "select count(*) from " + countSql.substring(countSql.toLowerCase().indexOf("from") + 5); Query query2 = this.createQuery(countSql); int paramIndex = 0; if (values != null) { for (int i = 0; i <= values.length - 1; i++) { if (operators != null && operators[i].equalsIgnoreCase("isnull")) continue; if (operators != null && operators[i].equalsIgnoreCase("isnotnull")) continue; if (operators != null && operators[i].equalsIgnoreCase("isempty")) continue; if (operators != null && operators[i].equalsIgnoreCase("isnotempty")) continue; query2.setParameter(paramIndex++, values[i]); } } // modi by denny Long res = (Long) query2.uniqueResult(); if (res != null) { count = res.intValue(); } } if (offset > 0) { query.setFirstResult(offset); } if (size > 0) { query.setMaxResults(size); } // ?log // logger.debug("fullSql=" + query.getQueryString()); map.put("list", query.list()); map.put("count", count); return new Object[] { map.get("list"), map.get("count") }; } 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. * * @param values * ???,??. */ public Query createQuery(final String queryString, final Map<String, Object> values) { Assert.hasText(queryString, "queryString?"); Query query = getSession().createQuery(queryString); if (values != null) { query.setProperties(values); } return query; } }