Java tutorial
package com.lyh.licenseworkflow.dao; import com.lyh.licenseworkflow.po.User; import com.lyh.licenseworkflow.system.OceanRuntimeException; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; import org.hibernate.Criteria; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.criterion.Criterion; import org.hibernate.criterion.Disjunction; import org.hibernate.criterion.Projections; import org.hibernate.criterion.Restrictions; import org.jbpm.api.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataAccessException; import org.springframework.orm.hibernate3.HibernateCallback; import org.springframework.orm.hibernate3.HibernateTemplate; import javax.annotation.Resource; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * @author kevin * @version Revision: 1.00 Date: 11-9-22?4:59 * @Email liuyuhui007@gmail.com */ public abstract class EnhancedHibernateDaoSupport<T> { @Autowired private HibernateTemplate hibernateTemplate; @Resource private ProcessEngine processEngine; protected RepositoryService repositoryService; protected ExecutionService executionService; protected TaskService taskService; protected HistoryService historyService; protected ManagementService managementService; protected IdentityService identityService; /** * ???MapNode.class.getName()?MapLink.class.getName() * * @return */ protected abstract String getEntityName(); /** * * * @return */ public List<T> getAllEntities() { return getHibernateTemplate().find("from " + getEntityName()); } /** * ??hql * * @param hql * @return */ public List<T> getEntityByHql(String hql) { String string = "from " + getEntityName() + hql; return getHibernateTemplate().find(string); } /** * ?null * * @param id ID * @return */ public T getById(Long id) { if (id == null) return null; return (T) (getHibernateTemplate().get(getEntityName(), id)); } /** * ???? * * @param name ?? * @return ? */ public T getByName(String name) { T result = null; List<T> list = (List<T>) getHibernateTemplate() .find("from " + getEntityName() + " where name='" + name + "'"); if (list != null && list.size() > 0) { result = list.get(0); } return result; } /** * ? * * @param entity * @return hibernate id ?? */ public long save(T entity) { return (Long) getHibernateTemplate().save(entity); } /** * ? * * @param entities */ public void saveOrUpdateAllEntities(Collection<T> entities) { if (entities.isEmpty()) return; getHibernateTemplate().saveOrUpdateAll(entities); } /** * ? * * @param entity */ public void update(T entity) { if (entity == null) return; getHibernateTemplate().update(entity); } /** * ?? * * @param entity */ public void saveOrUpdate(T entity) { if (entity == null) return; getHibernateTemplate().merge(entity); } /** * ?id * * @param id */ public void delete(Long id) { T entity = getById(id); if (entity == null) return; getHibernateTemplate().delete(entity); } /** * ? * * @param entity */ public void delete(T entity) { if (entity == null) return; getHibernateTemplate().delete(entity); } /** * ???????? * * @param selectedProps ??? * @param conditionKeys where??? * @param values where??? * @return ???? */ @SuppressWarnings("unchecked") public List<?> getEntityProperties(final String[] selectedProps, final String[] conditionKeys, final Object[] values) { if (ArrayUtils.isEmpty(selectedProps) || (!ArrayUtils.isEmpty(conditionKeys) && !ArrayUtils.isEmpty(values) && conditionKeys.length != values.length)) { throw new IllegalArgumentException("Invalid arguments to execute sql query."); } StringBuilder sql = new StringBuilder("select "); for (int i = 0, n = selectedProps.length; i < n; i++) { if (i != n - 1) sql.append(selectedProps[i] + ","); else sql.append(selectedProps[i] + " from "); } if (conditionKeys == null) { sql.append(getEntityName()); } else { sql.append(getEntityName() + " where "); for (int i = 0, n = conditionKeys.length; i < n; i++) { if (i != n - 1) { sql.append(conditionKeys[i]); sql.append(" = ? and "); } else { sql.append(conditionKeys[i]); sql.append(" = ?"); } } } return getHibernateTemplate().find(sql.toString(), values); } /** * ?? * * @param propertyNames * @param values * @return true??false */ @SuppressWarnings("unchecked") public boolean isEntityExisted(final String[] propertyNames, final Object[] values) { if (ArrayUtils.isEmpty(propertyNames) || ArrayUtils.isEmpty(values) || propertyNames.length != values.length) throw new IllegalArgumentException("Invalid arguments to execute sql query."); StringBuilder queryString = new StringBuilder("select id from " + getEntityName() + " where "); for (int i = 0, n = propertyNames.length; i < n; i++) { if (i != n - 1) queryString.append(propertyNames[i] + " = ? and "); else queryString.append(propertyNames[i] + " = ?"); } List result = getHibernateTemplate().find(queryString.toString(), values); return CollectionUtils.isNotEmpty(result); } /** * * * @param start ? - 0 * @param pageSize ?? * @return */ @SuppressWarnings("unchecked") public List<T> getPagingEntities(final int start, final int pageSize) { return (List<T>) getHibernateTemplate().execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { Criteria criteria = session.createCriteria(getEntityName()); criteria.setFirstResult(start); criteria.setMaxResults(pageSize); return criteria.list(); } }); } /** * ?hql * * @param start ? - 0 * @param pageSize ?? * @param hql * @return */ @SuppressWarnings("unchecked") public List<T> getPagingEntitiesByHql(final String hql, final int start, final int pageSize) { return (List<T>) getHibernateTemplate().execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { Query query = session.createQuery(hql); query.setFirstResult(start); query.setMaxResults(pageSize); return query.list(); } }); } /** * ? * * @param propertyNames ??? * @param values ??? * @param start ? - 0 * @param pageSize * @return */ @SuppressWarnings("unchecked") public List<T> getPagingEntitiesByPropName(final String[] propertyNames, final Object[] values, final int start, final int pageSize) { if (ArrayUtils.isEmpty(propertyNames) || ArrayUtils.isEmpty(values) || propertyNames.length != values.length) { throw new IllegalArgumentException("Invalid arguments to execute sql query."); } return (List<T>) getHibernateTemplate().execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { Criteria criteria = session.createCriteria(getEntityName()); for (int i = 0; i < propertyNames.length; i++) { if (values[i] == null) criteria.add(Restrictions.isNull(propertyNames[i])); else if (values[i].toString().indexOf("%") != -1) {// ,?value?% criteria.add(Restrictions.like(propertyNames[i], values[i])); } else { criteria.add(Restrictions.eq(propertyNames[i], values[i])); } } criteria.setFirstResult(start); criteria.setMaxResults(pageSize); return criteria.list(); } }); } public List<T> getPagingEntitiesByPropName(final String propertyName, final Object value, final int start, final int pageSize) { return getPagingEntitiesByPropName(new String[] { propertyName }, new Object[] { value }, start, pageSize); } /** * ?SQLor?? from DeviceResource where (type = 'ROUTER' or type = 'L3_SWITCH'); * <p/> * <p/> * Notes: or<br> * <br> * Create Author : allen.wang <br> * Create Date : 2009-3-18 * * @param start * @param pageSize * @param propertyName * @param values * @return */ @SuppressWarnings("unchecked") public List<T> getPagingEntitiesByOrCondition(final int start, final int pageSize, final String propertyName, final Object... values) { return (List<T>) getHibernateTemplate().execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { Criteria criteria = session.createCriteria(getEntityName()); Disjunction d = Restrictions.disjunction(); criteria = criteria.add(d); for (int i = 0; i < values.length; i++) d.add(Restrictions.eq(propertyName, values[i])); criteria.setFirstResult(start); criteria.setMaxResults(pageSize); return criteria.list(); } }); } /** * ???- * * @param propertyName * @param value */ public void deleteEntityByProperty(String propertyName, final Object value) { getHibernateTemplate().bulkUpdate("delete from " + getEntityName() + " where " + propertyName + " = ?", value); } /** * * * @param entities */ @SuppressWarnings("unchecked") public void deleteAllEntities(Collection<T> entities) { if (entities.isEmpty()) return; getHibernateTemplate().deleteAll(entities); } /** * ?? from DeviceResource where type = 'ROUTER' and temp = false and mgtIp = '192.168.0.8'; * ??? * <p/> * <p/> * ?{{@link #getEntitiesByPropNames(String[], Object[])} * * @param propertyNames ??? * @param values * @return ?? */ @SuppressWarnings("unchecked") public T getUniqueEntityByPropNames(final String[] propertyNames, final Object[] values) { List<T> result = getEntitiesByPropNames(propertyNames, values); if (!CollectionUtils.isEmpty(result)) return result.get(0); return null; } /** * ?? from DeviceResource where type = 'ROUTER' and temp = false; * * @param propertyNames ??? * @param values * @return ?? */ @SuppressWarnings("unchecked") public List<T> getEntitiesByPropNames(final String[] propertyNames, final Object[] values) { if (ArrayUtils.isEmpty(propertyNames) || ArrayUtils.isEmpty(values) || propertyNames.length != values.length) { throw new IllegalArgumentException("arguments is invalid."); } return (List<T>) getHibernateTemplate().execute(new HibernateCallback() { @Override public Object doInHibernate(Session session) throws HibernateException, SQLException { Criteria c = session.createCriteria(getEntityName()); for (int i = 0; i < propertyNames.length; i++) { String propertyName = propertyNames[i]; if (propertyName.indexOf(".") != -1) { Criteria subC = null; String[] props = StringUtils.split(propertyName, "."); for (int j = 0; j < props.length; j++) { if (j != props.length - 1) { subC = c.createCriteria(props[j]); } } if (values[i] == null) subC.add(Restrictions.isNull(propertyName.substring(propertyName.indexOf(".") + 1))); else subC.add(Restrictions.eq(propertyName.substring(propertyName.indexOf(".") + 1), values[i])); } else { if (values[i] == null) c.add(Restrictions.isNull(propertyNames[i])); else if (values[i].toString().indexOf("%") != -1) {// ,?value?% c.add(Restrictions.like(propertyNames[i], values[i])); } else { c.add(Restrictions.eq(propertyNames[i], values[i])); } } } return c.list(); } }); } /** * ??? from DeviceResource where (type = 'ROUTER' or type = 'L3_SWITCH');<br> * <br> * Create Author : allen.wang <br> * Create Date : 2009-3-18 * * @param propertyName * @param values * @return */ public int countEntitiesByOrCondition(final String propertyName, final Object... values) { return (Integer) getHibernateTemplate().execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { Criteria criteria = session.createCriteria(getEntityName()); Disjunction d = Restrictions.disjunction(); criteria = criteria.add(d); for (int i = 0; i < values.length; i++) d.add(Restrictions.eq(propertyName, values[i])); int num = ((Integer) criteria.setProjection(Projections.rowCount()).uniqueResult()).intValue();// ??? return new Integer(num); } }); } /** * ??? from DeviceResource where type = 'ROUTER' and temp = false; * * @param propertyNames ??? * @param values * @return ?? */ @SuppressWarnings("unchecked") public int countEntitiesByPropNames(final String[] propertyNames, final Object[] values) { if (ArrayUtils.isEmpty(propertyNames) || ArrayUtils.isEmpty(values) || propertyNames.length != values.length) { throw new IllegalArgumentException("arguments is invalid."); } return (Integer) getHibernateTemplate().execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { Criteria c = session.createCriteria(getEntityName()); for (int i = 0; i < propertyNames.length; i++) { String propertyName = propertyNames[i]; if (propertyName.indexOf(".") != -1) { Criteria subC = null; String[] props = StringUtils.split(propertyName, "."); for (int j = 0; j < props.length; j++) { if (j != props.length - 1) { subC = c.createCriteria(props[j]); } } if (values[i] == null) subC.add(Restrictions.isNull(propertyName.substring(propertyName.indexOf(".") + 1))); else subC.add(Restrictions.eq(propertyName.substring(propertyName.indexOf(".") + 1), values[i])); } else { if (values[i] == null) c.add(Restrictions.isNull(propertyNames[i])); else c.add(Restrictions.eq(propertyNames[i], values[i])); } } int num = ((Integer) c.setProjection(Projections.rowCount()).uniqueResult()).intValue();// ??? return new Integer(num); } }); } /** * ?<br> * <p/> * <pre> * : {{@link #countEntitiesByPropNames(String[], Object[]) ?</pre> * <br> * <br> * Create Author : allen.wang * <br> * Create Date : 2009-3-13 * * @param propertyNames * ??? * @param values * ??? * @return * */ public int countEntitiesByPropNames(final String propertyName, final Object value) { return countEntitiesByPropNames(new String[] { propertyName }, new Object[] { value }); } /** * ?? from DeviceResource where type = 'ROUTER' and temp = false; * * @param start ? * @param pageSize ?? * @param propertyNames ??? * @param values * @return ?? */ @SuppressWarnings("unchecked") public List<T> getPagingEntitiesByPropNames(final int start, final int pageSize, final String[] propertyNames, final Object[] values) { if (ArrayUtils.isEmpty(propertyNames) || ArrayUtils.isEmpty(values) || propertyNames.length != values.length) { throw new IllegalArgumentException("arguments is invalid."); } return (List<T>) getHibernateTemplate().execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { Criteria c = session.createCriteria(getEntityName()); c.setFirstResult(start); c.setMaxResults(pageSize); for (int i = 0; i < propertyNames.length; i++) { String propertyName = propertyNames[i]; if (propertyName.indexOf(".") != -1) { Criteria subC = null; String[] props = StringUtils.split(propertyName, "."); for (int j = 0; j < props.length; j++) { if (j != props.length - 1) { subC = c.createCriteria(props[j]); } } if (values[i] == null) subC.add(Restrictions.isNull(propertyName.substring(propertyName.indexOf(".") + 1))); else subC.add(Restrictions.eq(propertyName.substring(propertyName.indexOf(".") + 1), values[i])); } else { if (values[i] == null) c.add(Restrictions.isNull(propertyNames[i])); else if (values[i].toString().indexOf("%") != -1) {// ,?value?% c.add(Restrictions.like(propertyNames[i], values[i])); } else { c.add(Restrictions.eq(propertyNames[i], values[i])); } } } return c.list(); } }); } /** * ??? from DeviceResource where type = 'ROUTER'; * * @param propertyName ?? * @param value * @return ?? */ public List<T> getEntitiesByOneProperty(final String propertyName, final Object value) { return getEntitiesByPropNames(new String[] { propertyName }, new Object[] { value }); } /** * ?? * * @param propertyName ?? * @param value * @return ??null */ public T getUniqueEntityByOneProperty(final String propertyName, final Object value) { List<T> result = getEntitiesByOneProperty(propertyName, value); if (CollectionUtils.isNotEmpty(result)) return result.get(0); return null; } /** * ?SQLor?? from DeviceResource where (type = 'ROUTER' or type = 'L3_SWITCH'); * <p/> * <p/> * Notes: or * * @param propertyName ?? * @param values ? * @return ?? */ @SuppressWarnings("unchecked") public List<T> getEntitiesByOrCondition(final String propertyName, final Object... values) { return (List<T>) getHibernateTemplate().execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { Criteria c = session.createCriteria(getEntityName()); Disjunction d = Restrictions.disjunction(); c = c.add(d); for (int i = 0; i < values.length; i++) d.add(Restrictions.eq(propertyName, values[i])); return c.list(); } }); } /** * ID * * @param ids */ public void deletAllEntities(List<Long> ids) { StringBuffer sql = new StringBuffer("delete from " + getEntityName() + " where "); for (int i = 0; i < ids.size(); i++) { sql.append("id = "); sql.append(ids.get(i)); if (i != (ids.size() - 1)) sql.append(" or "); } getHibernateTemplate().bulkUpdate(sql.toString()); } /** * */ public void deleteAllEntities() { getHibernateTemplate().bulkUpdate("delete from " + getEntityName()); } // public Object delete @SuppressWarnings("unchecked") public List<T> getEntitiesByCriterion(final Criterion criterion) { return (List<T>) getHibernateTemplate().execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { Criteria c = session.createCriteria(getEntityName()); c.add(criterion); return c.list(); } }); } @SuppressWarnings("unchecked") public int count() { List<Number> list = getHibernateTemplate().find("select count(*) from " + getEntityName()); return Integer.parseInt(list.get(0).toString()); } /** * ??????? propertyName:bo?? propertyValue:?? * * @return ?true,?false */ @SuppressWarnings("unchecked") public boolean isConflictOneProperty(final String propertyName, final String propertyValue) { List<T> objects = getHibernateTemplate().find( "from " + getEntityName() + " where upper(" + propertyName + ") = ?", propertyValue.toUpperCase()); if (CollectionUtils.isEmpty(objects)) return false; else return true; } /** * ?? * * @param id Id * @param obj */ public void updateOceanObject(long id, Object obj) { T entity = getById(id); if (entity == null) throw new OceanRuntimeException(""); else getHibernateTemplate().merge(obj); } /** * ?Id?,true?false * * @param id Id */ public boolean isObjExist(long id) { T entity = getById(id); if (entity == null) return false; else return true; } /** * add by jonim ?HQL * * @param hql * @param firstRow * @param maxRow * @return */ @SuppressWarnings("unchecked") public List findList4Page(final String hql, final int firstRow, final int maxRow) { return this.getHibernateTemplate().executeFind(new HibernateCallback() { public Object doInHibernate(Session session) throws SQLException, HibernateException { Query q = session.createQuery(hql); q.setFirstResult(firstRow); q.setMaxResults(maxRow); return q.list(); } }); } public Integer executeUpdateHql(final String hql) throws OceanRuntimeException { try { return (Integer) this.getHibernateTemplate().execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { Query query = session.createQuery(hql); return Integer.valueOf(query.executeUpdate()); } }); } catch (DataAccessException e) { e.printStackTrace(); throw new OceanRuntimeException("executeUpdate is fail! hql:" + hql); } } /** * ????? * * @param start * @param limit * @param hql ?Hql? * @return */ public Object[] getFiexedObjectsInPage(final int start, final int limit, final String hql) { return (Object[]) getHibernateTemplate().execute(new HibernateCallback() { public Object doInHibernate(Session session) { String countHql = "select count(id) " + hql; Query countQuery = session.createQuery(countHql); int size = ((Long) countQuery.iterate().next()).intValue(); Query query = session.createQuery(hql); query.setFirstResult(start); query.setMaxResults(limit); return new Object[] { size, query.list() }; } }); } public HibernateTemplate getHibernateTemplate() { return hibernateTemplate; } public ProcessEngine getProcessEngine() { return processEngine; } public RepositoryService getRepositoryService() { if (repositoryService == null) { repositoryService = processEngine.getRepositoryService(); } return repositoryService; } public ExecutionService getExecutionService() { if (executionService == null) { executionService = processEngine.getExecutionService(); } return executionService; } public TaskService getTaskService() { if (taskService == null) { taskService = processEngine.getTaskService(); } return taskService; } public HistoryService getHistoryService() { if (null == historyService) historyService = processEngine.getHistoryService(); return historyService; } public ManagementService getManagementService() { if (null == managementService) managementService = processEngine.getManagementService(); return managementService; } public IdentityService getIdentityService() { if (null == identityService) identityService = processEngine.getIdentityService(); return identityService; } }