系统中常用操作基类(SSH项目中)非常非常经典的部分
package com.css.common.hibernate3;
?
import java.io.Serializable;
import java.util.List;
import java.util.Map;
?
?
/**
?* DB層的Dao-接口類 <br/>
?*
?* @author何青
?*/
publicinterfaceGenericHibernateDao<T> {
??? /**
???? *添加一個對象
???? * @param t
???? * @throws Exception
???? */
??? publicvoid save(T t)throws Exception;
?
??? /**
???? * 更新一對象
???? * @param t
???? * @throws Exception
???? */
??? publicvoid update(T t)throws Exception;
?
??? /**
???? * 加載一對象
???? * @param id
???? * @return T
???? * @throws Exception
???? */
??? public T load(Serializable id)throws Exception;
?
??? /**
???? * 獲取一對象
???? * @param id
???? * @return T
???? * @throws Exception
???? */
??? public T get(Serializable id)throws Exception;
?
??? /**
???? * 刪除一個對象
???? * @param o
???? * @throws Exception
???? */
??? publicvoid remove(Object o)throws Exception;
???
??? /**
???? * 將傳入的游離狀態的對象的屬性復制到持久化對象中,并返回該持久化對象。?
???? * 如果該session中沒有關聯的持久化對象,加載一個,如果傳入對象未保存,保存一個副本并作為持久對象返回,傳入對象依然保持游離狀態
???? * @param entity POJO實體
???? * @return持久化對象
???? * @throws Exception
???? */
??? public Object merge(Object entity)throws Exception;
?
??? /**
???? * 執行本地SQL語句
???? * 【注意:不能執行Select查詢語句】
???? * @param sql
???? * @throws Exception
???? */
??? publicvoid executeSQL(String sql)throws Exception;
?
? ??/**
???? * 執行本地SQL語句
???? * 【注意:只能執行Select查詢語句】
???? * @param sql
???? * @return List
???? * @throws Exception
???? */
??? @SuppressWarnings("unchecked")
??? public List listSQL(String sql)throws Exception;
?
??? ?/**
???? * 執行本地SQL語句
???? * 【注意:只能執行Select查詢語句】
???? * @param sql
???? * @param cache是否應用Hibernate的二級緩存<br/>true表示開啟 false 表示不開啟
???? * @return List
??? ?* @throws Exception
???? */
??? @SuppressWarnings("unchecked")
??? public List listSQL(String sql,boolean cache)throws Exception;
???
???
??? /**
??? ?* 執行本地SQL語句
??? ?* 【注意:只能執行Select查詢語句】
??? ?* @param sql
??? ?* @return查詢指定的字段值
??? ?* @throws Exception
??? ?*/
??? public Object valueSQL(final String sql)throws Exception;
??? /**
???
???? * 刪除
???? * @param tableName
???? * @param fieldName
???? * @param fieldValues [支持批量刪除]<br/>如:id=4或id="4,5"
???? * @throws Exception
???? */
??? publicvoid delete(String tableName, String fieldName, String fieldValues)throws Exception;
?
??? /**
???
???? * 刪除
???? * @param tableName
???? * @param map [支持多條件組合刪除]<br/>如:map.put("id",3),map.put("username","myname")
???? * @throws Exception
???? */
??? @SuppressWarnings("unchecked")
??? publicvoid delete(String tableName, Map map)throws Exception;
?
??? /**
???? * 更新對象
???? * @param hql
???? * @param params指定的參數
???? * @throws Exception
???? */
?? ?publicvoid update(String hql, Object[] params)throws Exception;
?
??? /**
???? * 批量更新實體
???? * @param tableName
???? * @param updateFieldName
???? * @param updateFieldValue
???? * @param updateKeyName
???? * @param updateKeyValue
???? * @return返回執行結果,-1表示失敗
???? * @throws Exception
???? */
??? publicvoid update(final String tableName, String updateFieldName, String updateFieldValue, String updateKeyName, String updateKeyValue)throws Exception;
?
??? /**
???? * 查詢VO對象列表<br/>
???? * 如:getHibernateTemplate().find(hql, params)
???? * @param hql HQL語句
???? * @param params指定的HQL語句帶的多個參數值
???? * @return數據集合
???? * @throws Exception
???? */
??? publicList list(String hql, Object[] params) throws Exception;
???
??? /**
???? * 查詢VO對象列表<br/>
???? * 如:Query query = session.createQuery(hql);query.setString(i,str);
???? * @param hql HQL語句
???? * @param values指定的HQL語句帶的多個參數值
???? * @return數據集合
???? * @throws Exception
???? */
??? publicList queryList(final String hql,final Object[] values)throws Exception;
???
??? /**
???? * 查詢VO對象列表<br/>
???? * 如:Query query = session.createQuery(hql);query.setString(i,str);
???? * @param hql HQL語句
???? * @param values指定的HQL語句帶的多個參數值
???? * @param cache是否應用Hibernate的二級緩存<br/>true表示開啟 false 表示不開啟
???? * @return數據集合
? ???* @throws Exception
???? */
??? publicList queryList(final String hql,final Object[] values,finalboolean cache)throws Exception;
???
??? /**
???? * 查詢Model對象列表<br/>
???? * 如:Query query = session.createSQLQuery(sql);query.setString(i,str);
???? * @param sqlBean封裝Model的SqlBean對象
???? * @return數據集合
???? * @throws Exception
???? */
??? publicList queryList(finalSqlBean sqlBean) throws Exception;
???
??? /**
???? * 查詢Model對象列表<br/>
???? * 如:Query query = session.createSQLQuery(sql);query.setString(i,str);
???? * @param sqlBean封裝Model的SqlBean對象
???? * @param cache是否應用Hibernate的二級緩存<br/>true表示開啟 false 表示不開啟
???? * @return數據集合
???? * @throws Exception
???? */
??? publicList queryList(finalSqlBean sqlBean,finalboolean cache)throws Exception;
?
??? /**
???? * 根據SQL語句進行分頁查詢
???? * @param curPage請求的當前頁
???? * @param pageSize每頁顯示多少行
???? * @param sqlBean封裝Model的SqlBean對象
???? * @return PageSupport封裝好的分頁對象
???? */
??? publicPageSupport queryPage(int curPage,int pageSize,SqlBean sqlBean)throws Exception;
???
??? /**
???? * 根據SQL語句進行分頁查詢
???? * @param curPage請求的當前頁
???? * @param pageSize每頁顯示多少行
???? * @param sqlBean封裝Model的SqlBean對象
???? * @param cache是否應用Hibernate的二級緩存<br/>true表示開啟 false 表示不開啟
???? * @return PageSupport封裝好的分頁對象
???? */
??? publicPageSupport queryPage(int curPage,int pageSize,SqlBean sqlBean,boolean cache)throws Exception;
???
??? /**
???? * 根據HQL語句進行分頁查詢
???? * @param curPage請求的當前頁
???? * @param pageSize每頁顯示多少行
???? * @param hql HQL語句
???? * @param values指定的HQL語句帶的多個參數值
???? * @return PageSupport封裝好的分頁對象
???? */
??? publicPageSupport queryPage(finalint curPage,finalint pageSize,final String hql,final Object[] values)throws Exception;
???
??? /**
???? * 根據HQL語句進行分頁查詢
???? * @param curPage請求的當前頁
???? * @param pageSize每頁顯示多少行
???? * @param hql HQL語句
???? * @param values指定的HQL語句帶的多個參數值
???? * @param cache是否應用Hibernate的二級緩存<br/>true表示開啟 false 表示不開啟
???? * @return PageSupport封裝好的分頁對象
???? */
??? @SuppressWarnings("unchecked")
??? public PageSupport queryPage(finalint curPage, finalint pageSize,final String hql,final Object[] values,finalboolean cache)throws Exception;
???
??? /**
???? * 獲取一個對象
???? * @param hql HQL語句
???? * @param values指定的參數數組
???? * @return查詢的唯一對象
???? * @throws Exception
???? */
??? public Object queryForObject(final String hql, final Object[] values)throws Exception;
???
??? /**
???? * 獲取一個對象
???? * @param hql HQL語句
???? * @param values指定的HQL語句帶的多個參數值
???? * @param cache是否應用Hibernate的二級緩存<br/>true表示開啟 false 表示不開啟
???? * @return查詢的唯一對象
???? * @throws Exception
???? */
??? public Object queryForObject(final String hql, final Object[] values,finalboolean cache)throws Exception;
?
}
?
?
接口的實現類:
package com.css.common.hibernate3;
?
import java.io.Serializable;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
?
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.util.Assert;
?
/**
?* DB層的Dao -實現類? <br/>
?*
?* @author 何青
?*/
public class GenericHibernateDaoImpl<T> extends HibernateDaoSupport implements GenericHibernateDao<T> {
???
??? private Class<T> concreteClass;
?
??? public GenericHibernateDaoImpl(Class<T> concreteClass) {
?????? ?this.concreteClass = concreteClass;
??? }
???
??? @SuppressWarnings("unchecked")
??? public T load(Serializable id) throws Exception {
??????? return (T)getHibernateTemplate().load(concreteClass, id);
??? }
?
??? @SuppressWarnings("unchecked")
??? public T get(Serializable id) throws Exception {
??????? return (T)getHibernateTemplate().get(concreteClass, id);
??? }
?
??? public void save(T t) throws Exception {
??????? getHibernateTemplate().save(t);
??? }
?
??? public void update(T t) throws Exception {
??????? getHibernateTemplate().update(t);
??? }
?
??? public void remove(Object o) throws Exception {
??????? getHibernateTemplate().delete(o);
??? }
???
??? public Object merge(Object entity) throws Exception {
?????? Assert.notNull(entity);
?????? return getSession().merge(entity);
??? }
?
??? public void delete(String tableName, String fieldName, String fieldValues) throws Exception {
??????? StringBuffer _hql = new StringBuffer();
??????? _hql.append(" delete from ").append(tableName);
??????? _hql.append(" where ").append(fieldName).append(" in (").append(fieldValues).append(")");
??????? executeSQL(_hql.toString());
??? }
?
??? @SuppressWarnings("unchecked")
???
??? public void delete(String tableName, Map map) throws Exception {
??????? if (map != null && map.size() > 0) {
??????? ??? StringBuffer _hql = new StringBuffer();
??????? ??? _hql.append(" delete from ");
??????????? _hql.append(tableName);
??????????? _hql.append(" where ");
??????????? Iterator iterator = map.entrySet().iterator();
??????????? while (iterator.hasNext()) {
??????????????? Map.Entry entity = (Map.Entry)iterator.next();
??????????????? _hql.append(entity.getKey()).append(" in (").append(entity.getValue()).append(")");
??????????????? _hql.append(" and ");
??????????? }
??????????? String sql = _hql.toString();
??????????? if (sql.trim().endsWith("and")) {
??????????? ??? sql = sql.substring(0, _hql.length() - 4);
??????????? }
??????????? executeSQL(sql);
??????? }
??? }
?
??? public void update(String hql, Object[] params) throws Exception {
??????? getHibernateTemplate().bulkUpdate(hql, params);
??? }
?
??? public void update(final String tableName, String updateFieldName, String updateFieldValue,
??????? String updateKeyName, String updateKeyValue) throws Exception{
??????? StringBuffer _hql = new StringBuffer();
??????? _hql.append(" update ").append(tableName);
??????? _hql.append(" set ").append(updateFieldName).append(" = ").append(updateFieldValue);
??????? _hql.append(" where ").append(updateKeyName).append(" in (").append(updateKeyValue).append(")");
??????? executeSQL(_hql.toString());
??? }
???
??? public void executeSQL(String sql) throws Exception {
??????? getSession().createSQLQuery(sql).executeUpdate();
??? }
???
??? @SuppressWarnings("unchecked")
??? public List listSQL(String sql) throws Exception {
??????? return listSQL(sql,false);
??? }
???
??? @SuppressWarnings("unchecked")
??? public List listSQL(String sql,boolean cache) throws Exception{
??? ??? Query query = getSession().createSQLQuery(sql);
??? ??? //? 設置Ehcache的二級緩存
??? ??? query.setCacheable(cache);
??? ??? return query.list();
??? }
???
??? @SuppressWarnings("unchecked")
??? public Object valueSQL(final String sql) throws Exception {
??? ??? return getHibernateTemplate().execute(
????????????? new HibernateCallback() {
????????????????? public Object doInHibernate(Session sess) throws HibernateException {
???????????????????? Query query = sess.createSQLQuery(sql);
???????????????????? return query.uniqueResult();
????????????????? }
????????????? }
?????? );
??? }
?
??? @SuppressWarnings("unchecked")
??? public List list(String hql, Object[] params) throws Exception{
??????? return getHibernateTemplate().find(hql, params);
??? }
???
??? public List queryList(final String hql, final Object[] values) throws Exception {
??? ??? return queryList(hql,values,false);
??? }
?
??? @SuppressWarnings("unchecked")
??? public List queryList(final String hql, final Object[] values,final boolean cache) throws Exception {
?????? ?return (List)getHibernateTemplate().execute(new HibernateCallback() {
??? ??????????? public Object doInHibernate(Session sess) {
??? ??????????????? Query query = sess.createQuery(hql);
??? ??????????????? //?設置Ehcache的二級緩存
??? ??????????????? query.setCacheable(cache);
?????????????????
??? ??????????????? setQueryParams(values, query);
??? ??????????????
??? ??????????????? return query.list();
??? ??????????? }
??? ??????? });
??? }
???
??? public List queryList(final SqlBean sqlBean) throws Exception {
??? ??? return queryList(sqlBean,false);
?? ?}
?
??? @SuppressWarnings("unchecked")
??? public List queryList(final SqlBean sqlBean,final boolean cache) throws Exception {
?????? ?return (List)getHibernateTemplate().execute(new HibernateCallback() {
??? ??????????? public Object doInHibernate(Session sess) {
???? ???????????????
??????????????????? Query query = getSessionQuery(sqlBean.toString(), sess, "sql");
??????????????????? //?設置Ehcache的二級緩存
??????????????????? query.setCacheable(cache);
???????????????????
??????????????????? setQueryParams(sqlBean.getParams(),query);
???????????????????
??????????????????? return getModels(sqlBean.getBeanNames(),query.list(),sqlBean.getModelClass(),null);
??? ??????????? }
??? ??????? });
??? }
??????
??? public Object queryForObject(final String hql, final Object[] values) throws Exception{
?????? return queryForObject(hql,values,false);
??? }
???
??? public Object queryForObject(final String hql, final Object[] values,final boolean cache) throws Exception{
?????? return getHibernateTemplate().execute(
????????????? new HibernateCallback() {
????????????????? public Object doInHibernate(Session sess) throws HibernateException {
???????????????????? Query query = sess.createQuery(hql);
??? ????????????????? //?設置Ehcache的二級緩存
???????????????????? query.setCacheable(cache);
???????????????????? if (values != null) {
???????????????????????? for (int i = 0; i < values.length; i++){
??????????????????????????? query.setParameter(i, values[i]);
???????????????????????? }
???????????????????? }
???????????????????? return query.uniqueResult();
????????????????? }
????????????? }
?????? );
??? }
?
??? @SuppressWarnings("unchecked")
??? public PageSupport queryPage(final int curPage, final int pageSize, final String hql, final Object[] values) throws Exception{
??????? return queryPage(curPage,pageSize,hql,values,false);
??? }
???
??? @SuppressWarnings("unchecked")
??? public PageSupport queryPage(final int curPage, final int pageSize, final String hql, final Object[] values,final boolean cache) throws Exception{
??????? return (PageSupport)getHibernateTemplate().execute(new HibernateCallback() {
??????????????? public Object doInHibernate(Session sess) throws HibernateException {
??????????????? ??? PageSupport ps = new PageSupport();
??????????????????? ps.setCurPage(curPage);
??????????????????? ps.setPageSize(pageSize);
???????????????????
??????????????????? Query query = sess.createQuery(hql);
??????????????????? //?設置Ehcache的二級緩存
??????????????????? query.setCacheable(cache);
???????????????????
????????????? ??????setQueryParams(values, query);
???????????????????
??????????????????? query.setFirstResult(ps.getStartIndex());
?????????????? ?????query.setMaxResults(pageSize);
???????????????????
??????????????????? setQueryTotalCount(hql, values, ps,cache,"hql");
???????????????????
??????????????????? ps.setItems(query.list());
??????????????????? return ps;
??????????????? }
??????????? }
??????? );
??? }
?
???
??? @SuppressWarnings("unchecked")
??? public PageSupport queryPage(final int curPage, final int pageSize, final SqlBean sqlBean) throws Exception {
??? ????? return queryPage(curPage,pageSize,sqlBean,false);
??? }
?
??? public PageSupport queryPage(final int curPage, final int pageSize,final SqlBean sqlBean,final boolean cache) throws Exception {
??????? return (PageSupport)getHibernateTemplate().execute(new HibernateCallback() {
????????????? public Object doInHibernate(Session sess) {
????????????? ? PageSupport ps = new PageSupport();
????????????????? ps.setCurPage(curPage);
????????????????? ps.setPageSize(pageSize);
?????????????????
????????????????? Query query = getSessionQuery(sqlBean.toString(), sess, "sql");
????????????????? //? 設置Ehcache的二級緩存
????????????????? query.setCacheable(cache);
?????????????????
????????????????? setQueryParams(sqlBean.getParams(),query);
?????????????????
????????????????? query.setFirstResult(ps.getStartIndex());
?????????????? ???query.setMaxResults(pageSize);
?????????????????
????????????????? if(sqlBean.getCountSql() != null && !sqlBean.getCountSql().equals("")){
??? ??????????????? ??Query countQuery = getSessionQuery(sqlBean.getCountSql(), sess, "sql");
??????????????? ??? ??setQueryParams(sqlBean.getCountParams(), countQuery);
??????????????? ??? ??Object objT = countQuery.uniqueResult();
??????????????? ??? ??if(objT instanceof BigDecimal){
??????????????? ?????? ??BigDecimal obj = (BigDecimal) objT;
??????????????? ?????? ??if (obj!=null) {
??????????????? ?????????? ??ps.setTotalCount(obj.intValue());
??????????????? ?????? ??}else{
??????????????? ?????????? ??ps.setTotalCount(0);
??????????????? ?????? ??}
? ????????????????? ??}else if(objT instanceof BigInteger){
??????????????? ?????? ??BigInteger obj = (BigInteger) objT;
??????????????? ?????? ??if (obj!=null) {
??????????????? ?????????? ??ps.setTotalCount(obj.intValue());
??????????????? ?????? ??}else{
??????????????? ?????????? ??ps.setTotalCount(0);
??????????????? ?????? ??}
??????????????? ??? ??}
????????????????? }else{
??????????????? ??? ??setQueryTotalCount(sqlBean.toString(), sqlBean.getParams(), ps,cache,"sql");
????????????????? }
????????????????? ps.setItems(getModels(sqlBean.getBeanNames(),query.list(),sqlBean.getModelClass(),curPage));
????????????????? return ps;
???????????????? }
????????? ? }
??????? );
??? }??
???
??? @SuppressWarnings("unchecked")
??? private List getModels(final List<String> beanNames,final List<Object> result,final Class beanClass,final Integer curPage) {
?????? List list=new ArrayList();
?????? for(Object obj : result){
?????????? try {
????????????? Object bean = beanClass.newInstance();
????????????? Class type = obj.getClass();
????????????? if(type.isArray()){
????????????????? Object objs[] = (Object[])obj;
????????????????? int num = curPage != null && curPage > 1 ? objs.length -1: objs.length;
????????????????? for(int i = 0; i < num ;i++){
???????????????????? Field f = getClassField(beanClass,beanNames.get(i));
???????????????????? f.setAccessible(true);
???????????????????? if(objs[i] instanceof Byte) {
???????????????????????? Byte tempB = (Byte) objs[i];
???????????????????????? Short tempS = tempB.shortValue();
???????????????????????? f.set(bean, tempS !=null ? tempS:null);
???????????????????? }else if(objs[i] instanceof BigInteger){
???????????????????????? BigInteger tempB = (BigInteger) objs[i];
???????????????????????? Integer tempS = tempB.intValue();
???????????????????????? f.set(bean, tempS !=null ? tempS:null);
???????????????????? }else if(objs[i] instanceof Character){
???????????????????????? Character tempB = (Character) objs[i];
???????????????????????? String tempS = tempB.toString();
???????????????????????? f.set(bean, tempS !=null ? tempS:null);
???????????????????? }else if(objs[i] instanceof BigDecimal){
???????????????????????? BigDecimal tempB阿2= (BigDecimal) objs[i];
???????????????????????? Long tempS = tempB.longValue();
???????????????????????? f.set(bean, tempS !=null ? tempS:null);
???????????????????? }else{
???????????????????????? f.set(bean, objs[i] !=null ? objs[i]:null);
???????????????????? }
???????????????????? f.setAccessible(false);
????????????????? }
????????????? }else{
????????????????? Field f = getClassField(beanClass,beanNames.get(0));
????????????????? f.setAccessible(true);
????????????????? if(obj instanceof Byte) {
???????????????????? Byte tempB = (Byte) obj;
???????????????????? Short tempS = tempB.shortValue();
???????????????????? f.set(bean, tempS !=null ? tempS:null);
????????????????? }else if(obj instanceof BigInteger){
???????????????????? BigInteger tempB = (BigInteger) obj;
???????????????????? Integer tempS = tempB.intValue();
???????????????????? f.set(bean, tempS !=null ? tempS:null);
????????????????? }else if(obj instanceof Character){
???????????????????? Character tempB = (Character) obj;
???????????????????? String tempS = tempB.toString();
???????????????????? f.set(bean, tempS !=null ? tempS:null);
????????????????? }else if(obj instanceof BigDecimal){
???????????????????? BigDecimal tempB = (BigDecimal) obj;
???????????????????? Long tempS = tempB.longValue();
???????????????????? f.set(bean, tempS !=null ? tempS:null);
????????????????? }else{
???????????????????? f.set(bean, obj !=null ? obj:null);
????????????????? }
????????????????? f.setAccessible(false);
????????????? }
????????????? list.add(bean);
?????????? } catch (Exception e) {
????????????? e.printStackTrace();
?????????? }
?????? }
?????? return list;
??? }
???
??? private Field getClassField(Class aClazz, String aFieldName) {?
??????? Field[] declaredFields = aClazz.getDeclaredFields();?
??????? for (Field field : declaredFields) {?
??????????? if (field.getName().equals(aFieldName)) {?
??????????? return field;
??????????? }?
??????? }?
??????? Class superclass = aClazz.getSuperclass();?
??????? if (superclass != null) {//簡單的遞歸一下?
??????????? return getClassField(superclass, aFieldName);?
??????? }?
??????? return null;?
??? }
???
??? private Query getSessionQuery(String s_hql,Session sess,String queryType){
?????? Query query = null;
?????? if("sql".equals(queryType)){
??????? ??? query = sess.createSQLQuery(s_hql);
??????? }else if("hql".equals(queryType)) {
??????? ??? query = sess.createQuery(s_hql);
??????? }else{
??????? ??? query = sess.createQuery(s_hql);
??????? }
?????? return query;
??? }
???
??? @SuppressWarnings("unchecked")
??? private void setQueryTotalCount(final String hql, final Object[] values, PageSupport ps,boolean cache,String queryType){
??? ??? int ids = hql.toUpperCase().indexOf(" FROM ");
??? ??? String _hql = hql;
??? ??? if (ids > 0) {
??? ??????? _hql = hql.substring(ids);
??? ??? }
??? ??? Object obj = queryForObjectCount("select count(*) " + _hql, values,cache,queryType);
??? ??? if (obj!=null) {
??? ??????? ps.setTotalCount(Integer.parseInt(String.valueOf(obj)));
??? ??? }else{
??? ??? ??? ps.setTotalCount(0);
??? ??? }
??? }
???
??? private Object queryForObjectCount(String s_hql, final Object[] values,boolean cache,String queryType){
??????? int idx = s_hql.toUpperCase().indexOf(" ORDER ");
??????? if (idx > 0) {
??????? ??? s_hql = s_hql.substring(0, idx);
??????? }
??????? Query query = getSessionQuery(s_hql,super.getSession(),queryType);
??????? //? 設置Ehcache的二級緩存
??????? query.setCacheable(cache);
??????? setQueryParams(values, query);
??????? return query.uniqueResult();
??? }
?
??? private void setQueryParams(final Object[] values, Query query){
???? ???if (values != null) {
??????????? for (int i = 0; i < values.length; i++) {
??????????????? if (values[i] instanceof Long) {
??????????????????? Long l = (Long)values[i];
??????????????????? query.setLong(i, l.longValue());
??????????????? } else if (values[i] instanceof Integer) {
??????????????????? Integer l = (Integer)values[i];
??????????????????? query.setInteger(i, l.intValue());
??????????????? } else if (values[i] instanceof String) {
??????????????????? String str = (String)values[i];
???????? ???????????query.setString(i, str);
??????????????? } else {
??????????????????? query.setParameter(i, values[i]);
??????????????? }
??????????? }
??????? }
??? }
???
}
?
?
?
package com.css.common.hibernate3;
?
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
?
import org.hibernate.cfg.Configuration;
import org.hibernate.mapping.Column;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.Table;
?
/**
?* Hibernate的輔助類,獲取表名和列名?????? <br/>
?*
?* @author何青
?*/
publicclassHibernateConfigUtil {
?
??? privatestatic ConfigurationhibernateConf =new Configuration();
?
??? @SuppressWarnings("unchecked")
??? privatestatic PersistentClass getPersistentClass(Class clazz) {
?
?????? synchronized (HibernateConfigUtil.class) {
?????????? PersistentClass pc = hibernateConf.getClassMapping(clazz.getName());
?
?????????? if (pc ==null) {
?
????????????? hibernateConf =hibernateConf.addClass(clazz);
?
????????????? pc = hibernateConf.getClassMapping(clazz.getName());
?
?????????? }
?
?????????? return pc;
?
?????? }
?
??? }
?
??? @SuppressWarnings("unchecked")
??? privatestatic Table getTable(Class clazz) {
?????? returngetPersistentClass(clazz).getTable();
??? }
?
??? /**
??? ?* 得到表名
??? ?*
??? ?* @param clazz
??? ?*??????????? 映射到數據庫的po類
??? ?* @return
??? ?*/
??? @SuppressWarnings("unchecked")
??? publicstatic String getTableName(Class clazz) {
?
?????? returngetTable(clazz).getName();
?
??? }
?
??? /**
??? ?* 得到表的主鍵名
??? ?*
??? ?* @param clazz
??? ?*??????????? 映射到數據庫的po類
??? ?* @return
??? ?*/
??? @SuppressWarnings("unchecked")
??? publicstatic String getPkColumnName(Class clazz) {
?
?????? returngetTable(clazz).getPrimaryKey().getColumn(0).getName();
?
??? }
?
??? /**
??? ?* 得到指定表的列名
??? ?*
??? ?* @param clazz
??? ?*??????????? 映射到數據庫的po類
??? ?* @param index
??? ?*??????????? 字段列的索引數
??? ?* @return
??? ?*/
??? @SuppressWarnings("unchecked")
??? publicstatic String getColumnName(Class clazz,int index) {
?????? Table table = getTable(clazz);
?????? int columnSize = table.getColumnSpan();
?????? if (index <= columnSize) {
?????????? return table.getColumn(index).getName();
?????? } else {
?????????? return"";
?????? }
??? }
?
??? /**
??? ?* 得到表的所有列名
??? ?* @param clazz映射到數據庫的po類
??? ?* @return
??? ?*/
??? @SuppressWarnings("unchecked")
??? publicstatic List<String> getColumnNames(Class clazz) {
?????? Iterator<Column> itr = getTable(clazz).getColumnIterator();
?????? List<String> columns = new ArrayList<String>();
?????? while (itr.hasNext()) {
?????????? Column tmp = itr.next();
?????????? columns.add(tmp.getName());
?????? }
?????? return columns;
?
??? }
}
?
?
?
?
package com.css.common.hibernate3;
?
/**
?* 1\分頁處理類
?* 2\JSON處理類????????????????????? <br/>
?*
?* @author 何青
?*/
import java.util.ArrayList;
import java.util.List;
?
public class PageSupport<T> {
?????? /**
?????? ?* 返回類型
?????? ?*/
?????? private String type;
?????? /**
?????? ?* 返回信息
?????? ?*/
?????? private String message;
?????? /**
?????? ?* 當前頁記錄內容集合
?????? ?*/
?????? private T items;
?????? /**
?????? ?* 總記錄數
?????? ?*/
?????? private Integer totalCount = 0;
?????? /**
?????? ?* 總頁數
?????? ?*/
?????? private Integer pageCount = 0 ;
?????? /**
?????? ?* 每頁顯示記錄數
?????? ?*/
?????? private Integer pageSize = 10;
?????? /**
?????? ?* 當前頁
?????? ?*/
?????? private Integer curPage = 1;
?????? /**
????? ?* 當前頁之前和之后顯示的頁數個數 <br/>如:假設當前頁是 6 共有11頁<br/>那么顯示分頁條會顯示 1 2 3 4 5 [6] 7 8 9 10 11
?????? ?*/
?????? private Integer num = 5;
?
?????? /**
?????? ?* 清空分頁字段信息<br/>
?????? ?* 避免totalCount,pageCount,pageSize,curPage,num字段付初始值
?????? ?*/
?????? public void setNull(){
????????????? totalCount = null;
????????????? pageCount = null;
????????????? pageSize = null;
????????????? curPage = null;
????????????? num = null;
?????? }
?
?????? /**
?????? ?* 計算總頁數
?????? ?*
?????? ?* @param totalCount
?????? ?*/
?????? public void setTotalCount(Integer totalCount) {
????????????? if (totalCount > 0) {
???????????????????? this.totalCount = totalCount;
?????? ????????????? this.pageCount = (totalCount + pageSize - 1) / pageSize;
????????????? }
?????? }
??????
?????? /**
?????? ?* 獲取總記錄數
?????? ?*
?????? ?* @return
?????? ?*/
?????? public Integer getTotalCount() {
????????????? return totalCount;
?????? }
?
?????? /**
?????? ?* 獲取每頁顯示記錄數
?????? ?*
?????? ?* @return
?????? ?*/
?????? public Integer getPageSize() {
????????????? return pageSize;
?????? }
?
?????? /**
?????? ?* 設置每頁顯示記錄數
?????? ?*
?????? ?* @param pageSize
?????? ?*/
?????? public void setPageSize(Integer pageSize) {
????????????? this.pageSize = pageSize;
?????? }
?
?????? /**
?????? ?* 得到當前頁數
?????? ?*
?????? ?* @return
?????? ?*/
?????? public Integer getCurPage() {
????????????? return curPage;
?????? }
?
?????? /**
?????? ?* 設置當前頁數
?????? ?*
?????? ?* @param curPage
?????? ?*/
?????? public void setCurPage(Integer curPage) {
????????????? this.curPage = curPage;
?????? }
?
?????? /**
?????? ?* 獲取當前頁之前或之后顯示的頁數個數
?????? ?*
?????? ?* @return
?????? ?*/
?????? public Integer getNum() {
????????????? return num;
?????? }
?
?????? /**
?????? ?* 設置當前頁之前或之后顯示的頁數個數
?????? ?*
?????? ?* @param num
?????? ?*/
?????? public void setNum(Integer num) {
????????????? this.num = num;
?????? }
?
?????? /**
?????? ?* 獲取當前頁記錄內容集合
?????? ?*
?????? ?* @return
?????? ?*/
?????? public T getItems() {
????????????? return items;
?????? }
?
?????? /**
?????? ?* 設置當前頁記錄內容集合
?????? ?*
?????? ?* @param items
?????? ?*/
?????? public void setItems(T items) {
????????????? this.items = items;
?????? }
?
?????? /**
?????? ?* 得到總頁數
?????? ?*
?????? ?* @return
?????? ?*/
?????? public Integer getPageCount() {
????????????? return pageCount;
?????? }
?
?????? /**
?????? ?* 設置頁總數
?????? ?*
?????? ?* @param pageCount
?????? ?*/
?????? public void setPageCount(Integer pageCount) {
????????????? this.pageCount = pageCount;
?????? }
?
?????? /**
?????? ?* 判斷是否有前一頁
?????? ?*
?????? ?* @return
?????? ?*/
?????? public boolean getIsPrev() {
????????????? if (curPage > 1) {
???????????????????? return true;
????????????? }
????????????? return false;
?????? }
?
?????? /**
?????? ?* 判斷是否有后一頁
?????? ?*
?????? ?* @return
?????? ?*/
?????? public boolean getIsNext() {
????????????? if (curPage < pageCount) {
???????????????????? return true;
????????????? }
????????????? return false;
?????? }
?
?????? /**
?????? ?* 當前頁的前num條頁假設當前頁是 6共有11頁如:1 2 3 4 5
?????? ?*
?????? ?* @return
?????? ?*/
?????? public List<Integer> getPrevPages() {
????????????? List<Integer> list = new ArrayList<Integer>();
????????????? int _frontStart = 1;
?
????????????? if (curPage > num) {
???????????????????? _frontStart = curPage - num;
????????????? }
?
????????????? for (int i = _frontStart; i < curPage; i++) {
???????????????????? list.add(i);
????????????? }
?
????????????? return list;
?????? }
?
?????? /**
?????? ?* 當前頁的后num條頁假設當前頁是 6共有11頁如:7 8 9 10 11
?????? ?*
?????? ?* @return
?????? ?*/
?????? public List<Integer> getNextPages() {
????????????? List<Integer> list = new ArrayList<Integer>();
????????????? int _endCount = num;
?
????????????? if (num < pageCount && (curPage + num) < pageCount) {
???????????????????? _endCount = curPage + _endCount;
????????????? } else {
???????????????????? _endCount = pageCount;
????????????? }
?
????????????? for (int i = curPage + 1; i <= _endCount; i++) {
???????????????????? list.add(i);
????????????? }
?
????????????? return list;
?????? }
?
?????? /**
?????? ?* 得到起始頁數據
?????? ?*
?????? ?* @return
?????? ?*/
?????? public Integer getStartIndex() {
?
????????????? if (curPage > 0) {
???????????????????? return (curPage - 1) * pageSize;
????????????? }
????????????? return 0;
?????? }
?
?????? /**
?????? ?* 查詢是否有數據
?????? ?*
?????? ?* @return
?????? ?*/
?????? public boolean getIsPage() {
????????????? if (this.totalCount > 0) {
???????????????????? return true;
????????????? } else {
???????????????????? return false;
????????????? }
?????? }
?????? /**
?????? ?* 獲取前一頁
?????? ?*
?????? ?* @return
?????? ?*/
?????? public Integer getPrev() {
????????????? return curPage - 1;
?????? }
??????
?????? /**
?????? ?* 獲取后一頁
?????? ?* @return
?????? ?*/
?????? public int getNext(){
????????????? return curPage+1;
?????? }
??????
?????? /**
?????? ?* 獲取最后一頁
?????? ?*
?????? ?* @return
?????? ?*/
?????? public Integer getLast() {
????????????? return pageCount;
?????? }
??????
?????? /**
?????? ?* 得到返回類型
?????? ?* @return
?????? ?*/
?????? public String getType() {
????????????? return type;
?????? }
?
?????? /**
?????? ?* 設置返回類型
?????? ?* @param type
?????? ?*/
?????? public void setType(String type) {
????????????? this.type = type;
?????? }
?
?????? /**
?????? ?* 得到返回信息
?????? ?* @return
?????? ?*/
?????? public String getMessage() {
????????????? return message;
?????? }
?
?????? /**
?????? ?* 設置返回信息
?????? ?* @param message
?????? ?*/
?????? public void setMessage(String message) {
????????????? this.message = message;
?????? }
}
?
?
?
?
?
?
?
package com.css.common.hibernate3;
?
import java.util.ArrayList;
import java.util.List;
?
/**
?* SQL和實體Bean的映射處理 ??????????????????? <br/>
?*
?* @author 何青
?*/
public class SqlBean<T> {
??????
?????? private Class<T> clazz;
??????
?????? public SqlBean(){
?????????????
?????? }
??????
??? public SqlBean(Class<T> clazz) {
??????? this.clazz = clazz;
??? }
??????
?????? private List<String> beanNames = new ArrayList<String>();
??????
?????? private List<String> columnNames = new ArrayList<String>();
??????
?????? private String where;
??????
?????? private Object[] params = null;
??????
?????? private String countSql;
??????
?????? private Object[] countParams = null;
??????
?????? public void setColumnBeanNames(String columnName,String beanName)
?????? {
????????????? this.columnNames.add(columnName+" as "+beanName);
????????????? this.beanNames.add(beanName);
?????? }
??????
?????? public void removeColumnBeanNames(String columnName,String beanName)
?????? {
????????????? this.columnNames.remove(columnName+" as "+beanName);
????????????? this.beanNames.remove(beanName);
?????? }
??????
?????? public String getColumnNames()
?????? {
????????????? return this.columnNames.toString().substring(1,this.columnNames.toString().length()-1);
?????? }
??????
?????? public List<String> getBeanNames()
?????? {
????????????? return this.beanNames;
?????? }
?
?????? public Class<T> getModelClass() {
????????????? return this.clazz;
?????? }
??????
?????? public String getWhere() {
????????????? return where;
?????? }
?
?????? public void setWhere(String where) {
????????????? this.where = where;
?????? }
?
?????? public Object[] getParams() {
????????????? return params;
?????? }
?
?????? public void setParams(Object[] params) {
????????????? this.params = params;
?????? }
?
?????? public String getCountSql() {
????????????? return countSql;
?????? }
?
?????? public void setCountSql(String countSql) {
????????????? this.countSql = countSql;
?????? }
?
?????? public Object[] getCountParams() {
????????????? return countParams;
?????? }
?
?????? public void setCountParams(Object[] countParams) {
????????????? this.countParams = countParams;
?????? }
?
?????? @Override
?????? public String toString()
?????? {
????????????? return "select "+this.getColumnNames()+" "+this.getWhere();
?????????????
?????? }
??????
}
?
?
?
?
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的系统中常用操作基类(SSH项目中)非常非常经典的部分的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 天津南开第一干休所属于军队吗
- 下一篇: IExcelExport