package com.zxwl.base.dao;
import com.zxwl.common.log.ILogger;
import com.zxwl.common.log.LoggerManager;
import com.zxwl.common.util.GenericsUtils;
import java.io.Serializable;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Resource;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.dialect.Dialect;
import org.hibernate.impl.SessionFactoryImpl;
import org.hibernate.property.Getter;
import org.hibernate.property.Setter;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
public abstract class BaseDao<T>
implements IBaseDao<T>
{
protected Class<T> entityClass = GenericsUtils.getSuperClassGenricType(getClass());
protected EntityHelper<T> entityHelper;
protected Getter timestampGetter;
protected Setter timestampSetter;
protected Getter idGetter;
protected HibernateTemplate hibernateTemplate;
protected ILogger logger;
public <T> BaseDao()
{
this.logger = LoggerManager.getLogger(this);
_getEntityHelper();
}
public String getTimestamp()
{
return new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
}
protected EntityHelper<T> _getEntityHelper()
{
try
{
if (this.entityHelper == null)
{
this.entityHelper = new EntityHelper(this.entityClass);
if (this.entityHelper != null)
{
PropertyInfo timestampProp = this.entityHelper.getProperty("TIMESTAMP");
if (timestampProp != null)
{
this.timestampGetter = timestampProp.getGetter();
this.timestampSetter = timestampProp.getSetter();
}
else
{
this.logger.debug(this.entityClass.getName() + "获取TimeStamp Get ,Set函数失败!");
}
PropertyInfo idProp = this.entityHelper.getProperty("ID");
if (idProp != null)
{
this.idGetter = idProp.getGetter();
}
}
}
}
catch (Exception e)
{
this.logger.error("获取反射信息异常!", e);
}
return this.entityHelper;
}
public T createEntity() throws InstantiationException, IllegalAccessException
{
return this.entityClass.newInstance();
}
public HibernateTemplate getHibernateTemplate()
{
return this.hibernateTemplate;
}
@Resource
public void setHibernateTemplate(HibernateTemplate hibernateTemplate)
{
this.hibernateTemplate = hibernateTemplate;
}
public IProcedure<T> getProcedure()
{
IProcedure procedure = null;
SessionFactoryImpl sessionFactory = (SessionFactoryImpl)getHibernateTemplate().getSessionFactory();
Dialect dialect = sessionFactory.getDialect();
String dialectType = dialect.toString().toLowerCase();
if (dialectType.indexOf("oracle") > 0)
{
procedure = new ProcedureOracle(_getEntityHelper());
}
else if (dialectType.indexOf("sqlserver") > 0)
{
procedure = new ProcedureSqlServer(_getEntityHelper());
}
procedure.setHibernateTemplate(getHibernateTemplate());
return procedure;
}
protected List<T> _queryList(final String hql, final QueryParameter queryparameter)
{
return (List)getHibernateTemplate().execute(new HibernateCallback()
{
public Object doInHibernate(Session session)
throws HibernateException, SQLException
{
Query query = session.createQuery(hql);
BaseDao.this._setQueryParams(query, queryparameter);
return query.list();
}
});
}
public List<T> queryAll()
{
return (List)getHibernateTemplate().execute(new HibernateCallback()
{
public List<T> doInHibernate(Session session)
throws HibernateException, SQLException
{
return session.createQuery(" from " + BaseDao.this.entityClass.getSimpleName()).list();
}
});
}
public T queryById(Serializable entityId)
{
return getHibernateTemplate().get(this.entityClass, entityId);
}
public void save(T entity)
{
updateTimestamp(entity);
getHibernateTemplate().save(entity);
}
public void delete(Serializable[] entityIds)
{
for (Serializable serId : entityIds)
{
getHibernateTemplate().delete(getHibernateTemplate().load(this.entityClass, serId));
}
}
public void delete(Serializable entityId)
{
getHibernateTemplate().delete(getHibernateTemplate().load(this.entityClass, entityId));
}
public void update(T entity)
{
updateTimestamp(entity);
getHibernateTemplate().update(entity);
}
protected Object _query(final String hql, final QueryParameter queryParameter)
{
return getHibernateTemplate().execute(new HibernateCallback()
{
public Object doInHibernate(Session session)
throws HibernateException, SQLException
{
Query query = session.createQuery(hql);
BaseDao.this._setQueryParams(query, queryParameter);
return query.uniqueResult();
}
});
}
public Integer executeUpdate(final String hql)
{
return (Integer)getHibernateTemplate().execute(new HibernateCallback()
{
public Object doInHibernate(Session session)
throws HibernateException, SQLException
{
Integer query = Integer.valueOf(session.createQuery(hql).executeUpdate());
return query;
}
});
}
protected long _queryRowCount(String hql, final QueryParameter queryParams)
{
String lowerhql = hql.toLowerCase();
String hqltemp;
/* String hqltemp;*/
if ("select".equals(lowerhql.substring(0, 5)))
{
int fromPos = lowerhql.indexOf("from");
hqltemp = "select count(*) " + hql.substring(fromPos);
}
else
{
hqltemp = "select count(*) " + hql;
}
lowerhql = hqltemp.toLowerCase();
int index = lowerhql.indexOf(" order ");
if (index > 0)
{
hqltemp = hqltemp.substring(0, index);
}
final String hqlofCount = hqltemp;
return ((Long)getHibernateTemplate().execute(new HibernateCallback()
{
public Object doInHibernate(Session session)
throws HibernateException, SQLException
{
Query query = session.createQuery(hqlofCount);
BaseDao.this._setQueryParams(query, queryParams);
Object o = query.uniqueResult();
Long result = (Long)o;
Hibernate.initialize(result);
return result;
}
})).longValue();
}
protected void _setQueryParams(Query query, QueryParameter queryParameter)
{
if (queryParameter == null)
{
return;
}
Set<String> names = queryParameter.findParameterNames();
names.remove("pageSize");
names.remove("pageNum");
for (String name : names)
{
Parameter parameter = queryParameter.findParameter(name);
if ((parameter != null) && (queryParameter.containParameter(name).booleanValue()))
{
query.setParameter(name, parameter.findValue());
}
}
}
protected static void setQueryParams(Query query, Object[] queryParams) {
if (queryParams != null)
{
int i = 0;
for (Object param : queryParams)
{
query.setParameter(i, param);
i++;
}
}
}
protected List<T> _queryForPage(final String hql, final QueryParameter queryParams, final Integer pageNum, final Integer pageSize)
{
return getHibernateTemplate().executeFind(new HibernateCallback()
{
public Object doInHibernate(Session session)
throws HibernateException, SQLException
{
Query query = session.createQuery(hql);
BaseDao.this._setQueryParams(query, queryParams);
query.setFirstResult((pageNum.intValue() - 1) * pageSize.intValue());
query.setMaxResults(pageSize.intValue());
return query.list();
}
});
}
public List<Map<String, String>> queryMapListByProcedure(String procedureName, QueryParameter queryParameter)
{
return getProcedure().queryMapList(procedureName, queryParameter);
}
public void queryForPageByProcedure(String procedureName, DataPage<T> dataPage)
{
Integer beginIndex = Integer.valueOf((dataPage.getPageNum() - 1) * dataPage.getPageSize());
Integer endIndex = Integer.valueOf(beginIndex.intValue() + dataPage.getPageSize());
Integer rowSum = Integer.valueOf(0);
QueryParameter queryParameter = dataPage.getQueryParameter();
if (queryParameter == null)
{
queryParameter = new QueryParameter();
dataPage.setQueryParameter(queryParameter);
}
queryParameter.addParameter("beginIndex", beginIndex);
queryParameter.addParameter("endIndex", endIndex);
queryParameter.addOutParameter("rowSum", rowSum);
List list = queryListByProcedure(procedureName, queryParameter);
dataPage.setDataList(list);
dataPage.setRowSum(((Integer)queryParameter.findParameterValue("rowSum")).intValue());
}
public void queryMapListForPageByProcedure(String procedureName, DataPage<Map<String, String>> dataPage)
{
Integer beginIndex = Integer.valueOf((dataPage.getPageNum() - 1) * dataPage.getPageSize());
Integer endIndex = Integer.valueOf(beginIndex.intValue() + dataPage.getPageSize());
QueryParameter queryParameter = dataPage.getQueryParameter();
if (queryParameter == null)
{
queryParameter = new QueryParameter();
dataPage.setQueryParameter(queryParameter);
}
Parameter parameter = new Parameter("beginIndex", String.class);
parameter.setValue(beginIndex);
queryParameter.addParameter(parameter);
parameter = new Parameter("endIndex", String.class);
parameter.setValue(endIndex);
queryParameter.addParameter(parameter);
parameter = new Parameter("rowSum", String.class);
parameter.setValue(Integer.valueOf(0));
queryParameter.addOutParameter(parameter);
List list = queryMapListByProcedure(procedureName, queryParameter);
dataPage.setDataList(list);
dataPage.setRowSum(Integer.parseInt((String)queryParameter.findParameterValue("rowSum")));
}
public List<T> queryListByProcedure(String procedureName, QueryParameter queryParameter)
{
return getProcedure().queryList(procedureName, queryParameter);
}
public void executeProcedure(String procedureName, QueryParameter queryParameter)
{
getProcedure().execute(procedureName, queryParameter);
}
protected List<T> _queryForPage(DataPage<T> dataPage)
{
dataPage.setRowSum((int)_queryRowCount(dataPage.getHql(), dataPage.getQueryParameter()));
dataPage.setDataList(_queryForPage(dataPage.getHql(), dataPage.getQueryParameter(), Integer.valueOf(dataPage.getPageNum()), Integer.valueOf(dataPage.getPageSize())));
return dataPage.getDataList();
}
public void save(List<T> entity)
{
try
{
int i = 0;
for (T t : entity)
{
updateTimestamp(t);
this.hibernateTemplate.save(t);
if (i % 10 == 0)
{
this.hibernateTemplate.flush();
this.hibernateTemplate.clear();
i = 0;
}
else {
i++;
}
}
} catch (Exception e) {
this.logger.error("批量保存异常!", e);
}
}
@SuppressWarnings("unchecked")
public void executeSqlToUpdate(final String hql)
{
getHibernateTemplate().execute(new HibernateCallback()
{
public Object doInHibernate(Session session) throws SQLException, HibernateException
{
Query query = session.createQuery(hql);
query.executeUpdate();
return null;
}
});
}
public T query(QueryParameter queryParamter)
{
this.logger.warn("执行空函数!");
return null;
}
public List<T> queryList(QueryParameter queryParameter)
{
this.logger.warn("执行空函数!");
return null;
}
public long queryRowCount(QueryParameter queryParams)
{
this.logger.warn("执行空函数!");
return 0L;
}
public abstract List<T> queryForPage(DataPage<T> paramDataPage);
public Boolean isChanged(T entity)
{
this.logger.debug("检查记录是否改变");
if ((entity == null) || (this.timestampGetter == null) || (this.idGetter == null))
{
this.logger.debug("getter==null");
return Boolean.valueOf(false);
}
Object value = this.timestampGetter.get(entity);
if (value == null)
{
this.logger.debug("entity timestamp 为 null");
return Boolean.valueOf(false);
}
String timestamp = (String)value;
Object oldEntity = queryById((Integer)this.idGetter.get(entity));
if (oldEntity == null)
{
return Boolean.valueOf(true);
}
String oldTimeStamp = (String)this.timestampGetter.get(oldEntity);
return Boolean.valueOf(!timestamp.equals(oldTimeStamp));
}
public void updateTimestamp(T entity)
{
if (this.timestampSetter != null)
{
this.timestampSetter.set(entity, getTimestamp(), null);
}
else
{
this.logger.debug("更新TimeStamp失败!");
}
}
}
baseDao
最新推荐文章于 2021-11-24 15:35:41 发布