BaseDao.java
- import java.io.Serializable;
- import java.util.Collection;
- import java.util.List;
- import java.util.Map;
- import com.xxx.finance.utils.HibernateHandler;
- import com.xxx.finance.utils.Pagination;
- public interface BaseDao<T> {
- /**
- * 保存实体
- *
- * @param entity
- * 实体对象
- * @return 实体主键
- */
- Object save(Object entity);
- /**
- *
- * 删除实体
- *
- * @param entity
- * 实体对象
- *
- */
- void delete(Object entity);
- /**
- *
- * 更新实体
- *
- * @param entity
- * 实体对象
- *
- */
- void update(Object entity);
- /**
- *
- * 保存或更新实体, 实体没有主键时保存,否则更新
- *
- * @param entity
- * 实体对象
- *
- */
- void saveOrUpdate(Object entity);
- /**
- *
- * 批量保存实体
- *
- * @param entities
- * 实体集合
- */
- void saveAll(Collection<?> entities);
- /**
- *
- * 批量删除实体
- *
- * @param entities
- * 实体集合
- *
- */
- void deleteAll(Collection<?> entities);
- /**
- *
- * 批量更新实体
- *
- * @param entities
- * 实体集合
- *
- */
- void updateAll(Collection<?> entity);
- /**
- *
- * 批量保存或更新实体, 实体没有主键时保存,否则更新
- *
- * @param entity
- * 实体集合
- *
- */
- void saveOrUpdateAll(Collection<?> entities);
- /**
- *
- * 获取单个实体,根据实体类及实体的主键获取。
- *
- * @param entityClass
- * 实体类
- * @param id
- * 实体主键
- * @return 实体对象
- */
- @SuppressWarnings("hiding")
- <T> T get(Class<T> entityClass, Serializable id);
- /**
- * 获取单个实体,根据查询语句及参数获取。
- *
- * @param queryString
- * 查询语句
- * @param params
- * 可选的查询参数
- * @return 单个实体,如果查询结果有多个,则返回第一个实体
- */
- @SuppressWarnings("hiding")
- <T> T get(CharSequence queryString, Map<String, Object> params);
- /**
- * 获取单个实体,根据查询语句及参数获取。
- *
- * @param queryString
- * 查询语句
- * @param params
- * 可选的查询参数
- * @return 单个实体,如果查询结果有多个,则返回第一个实体
- */
- @SuppressWarnings("hiding")
- <T> T get(CharSequence queryString, Object... params);
- /**
- *
- * 查询实体列表
- *
- * @param queryString
- * 查询语句
- * @param params
- * 可选的查询参数
- * @return 实体列表
- */
- @SuppressWarnings("hiding")
- <T> List<T> findList(CharSequence queryString, Object... params);
- /**
- *
- * 查询实体列表
- *
- * @param queryString
- * 查询语句
- * @param params
- * 可选的查询参数
- * @return 实体列表
- */
- @SuppressWarnings("hiding")
- <T> List<T> findList(CharSequence queryString, Map<String, Object> params);
- /**
- * 分页查询实体
- *
- * @param queryString
- * 查询语句
- * @param pageIndex
- * 当前页码,如果pageIndex<1则不分页,且返回pageSize条记录。
- * @param pageSize
- * 每页记录数,如果pageSize<1则返回所有记录。
- * @param params
- * 可选的查询参数
- * @return 实体分页对象
- */
- @SuppressWarnings("hiding")
- <T> Pagination<T> findPagination(CharSequence queryString, int pageIndex, int pageSize, Object... params);
- /**
- * 分页查询实体
- *
- * @param queryString
- * 查询语句
- * @param params
- * 可选的查询参数
- * @param pageIndex
- * 当前页码,如果pageIndex<2则不分页,且返回pageSize条记录。
- * @param pageSize
- * 每页记录数,如果pageSize<1则返回所有记录。
- *
- * @return 实体分页对象
- */
- @SuppressWarnings("hiding")
- <T> Pagination<T> findPagination(CharSequence queryString, Map<String, Object> params, int pageIndex, int pageSize);
- /**
- * 分页查询实体,自定义总条数查询语句,适合复杂的hql分页查询
- *
- * @param queryString
- * 查询语句
- * @param countString
- * 查询记录总条数语句
- * @param pageIndex
- * 当前页码,如果pageIndex<1则不分页,且返回pageSize条记录。
- * @param pageSize
- * 每页记录数,如果pageSize<1则返回所有记录。
- * @param params
- * 可选的查询参数
- * @return 实体分页对象
- */
- @SuppressWarnings("hiding")
- <T> Pagination<T> findPagination(CharSequence queryString, CharSequence countString, int pageIndex, int pageSize,
- Object... params);
- /**
- * 分页查询实体,自定义总条数查询语句,适合复杂的hql分页查询
- *
- * @param queryString
- * 查询语句
- * @param countString
- * 查询记录总条数语句
- * @param params
- * 可选的查询参数
- * @param pageIndex
- * 当前页码,如果pageIndex<2则不分页,且返回pageSize条记录。
- * @param pageSize
- * 每页记录数,如果pageSize<1则返回所有记录。
- *
- * @return 实体分页对象
- */
- @SuppressWarnings("hiding")
- <T> Pagination<T> findPagination(CharSequence queryString, CharSequence countString, Map<String, Object> params,
- int pageIndex, int pageSize);
- /**
- * 分页查询实体,自定义总条数查询语句,适合复杂的sql分页查询
- *
- * @param queryString
- * 查询语句
- * @param countString
- * 查询记录总条数语句
- * @param params
- * 可选的查询参数
- * @param pageIndex
- * 当前页码,如果pageIndex<2则不分页,且返回pageSize条记录。
- * @param pageSize
- * 每页记录数,如果pageSize<1则返回所有记录。
- *
- * @return 实体分页对象
- */
- @SuppressWarnings("hiding")
- public <T> Pagination<T> findSqlPagination(final CharSequence queryString, final CharSequence countString,
- final Map<String, Object> params, int pageIndex, int pageSize);
- /**
- * 执行数据库更新操作
- *
- * @deprecated 用{@link #executeUpdate(String)}替换
- * @param hql
- */
- void execute(String hql);
- /**
- * 执行数据库更新操作
- *
- * @deprecated 用{@link #executeUpdate(HibernateHandler)}替换
- * @param hql
- */
- void execute(HibernateHandler handler);
- /**
- * 执行数据库更新操作
- *
- * @deprecated 用{@link #executeSqlUpdate(String)}替换
- * @param sql
- */
- void executeSql(String sql);
- /**
- * 执行数据库查询操作
- *
- * @param handler
- * 处理器
- * @return
- * @throws Exception
- */
- Object executeQuery(HibernateHandler handler);
- /**
- * 执行数据库更新操作
- *
- * @param sql
- * @return 更新的记录条数
- */
- int executeSqlUpdate(String sql);
- /**
- * 执行数据库更新操作
- *
- * @param hql
- * @return 更新的记录条数
- */
- int executeUpdate(String hql);
- /**
- * 执行数据库更新操作
- *
- * @param handler
- * 处理器
- * @return
- * @throws Exception
- */
- Object executeUpdate(HibernateHandler handler);
- public T getById(Serializable id);
- public T saveEntity(T o);
- public T insert(T o);
- public void save(List<T> list);
- public void insert(List<T> list);
- public void delete(List<T> list);
- public void update(List<T> list);
- public List<T> findByProperty(String name, Object value);
- public List<T> findByProperty(Map<String, Object> conditionMap);
- /**
- *
- * 查询实体列表
- *
- * @param queryString
- * 查询语句
- * @param maxResults
- * 列表最大数
- * @param params
- * 可选的查询参数
- * @return 实体列表
- */
- public <V> List<V> findListByMax(CharSequence queryString, int maxResults, Object... params);
- /**
- *
- * 查询实体列表
- *
- * @param queryString
- * 查询语句
- * @param maxResults
- * 列表最大数
- * @param params
- * 可选的查询参数
- * @return 实体列表
- */
- public <V> List<V> findListByMax(CharSequence queryString, int maxResults, Map<String, Object> params);
- }
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import com.xxx.finance.utils.HibernateHandler;
import com.xxx.finance.utils.Pagination;
public interface BaseDao<T> {
/**
* 保存实体
*
* @param entity
* 实体对象
* @return 实体主键
*/
Object save(Object entity);
/**
*
* 删除实体
*
* @param entity
* 实体对象
*
*/
void delete(Object entity);
/**
*
* 更新实体
*
* @param entity
* 实体对象
*
*/
void update(Object entity);
/**
*
* 保存或更新实体, 实体没有主键时保存,否则更新
*
* @param entity
* 实体对象
*
*/
void saveOrUpdate(Object entity);
/**
*
* 批量保存实体
*
* @param entities
* 实体集合
*/
void saveAll(Collection<?> entities);
/**
*
* 批量删除实体
*
* @param entities
* 实体集合
*
*/
void deleteAll(Collection<?> entities);
/**
*
* 批量更新实体
*
* @param entities
* 实体集合
*
*/
void updateAll(Collection<?> entity);
/**
*
* 批量保存或更新实体, 实体没有主键时保存,否则更新
*
* @param entity
* 实体集合
*
*/
void saveOrUpdateAll(Collection<?> entities);
/**
*
* 获取单个实体,根据实体类及实体的主键获取。
*
* @param entityClass
* 实体类
* @param id
* 实体主键
* @return 实体对象
*/
@SuppressWarnings("hiding")
<T> T get(Class<T> entityClass, Serializable id);
/**
* 获取单个实体,根据查询语句及参数获取。
*
* @param queryString
* 查询语句
* @param params
* 可选的查询参数
* @return 单个实体,如果查询结果有多个,则返回第一个实体
*/
@SuppressWarnings("hiding")
<T> T get(CharSequence queryString, Map<String, Object> params);
/**
* 获取单个实体,根据查询语句及参数获取。
*
* @param queryString
* 查询语句
* @param params
* 可选的查询参数
* @return 单个实体,如果查询结果有多个,则返回第一个实体
*/
@SuppressWarnings("hiding")
<T> T get(CharSequence queryString, Object... params);
/**
*
* 查询实体列表
*
* @param queryString
* 查询语句
* @param params
* 可选的查询参数
* @return 实体列表
*/
@SuppressWarnings("hiding")
<T> List<T> findList(CharSequence queryString, Object... params);
/**
*
* 查询实体列表
*
* @param queryString
* 查询语句
* @param params
* 可选的查询参数
* @return 实体列表
*/
@SuppressWarnings("hiding")
<T> List<T> findList(CharSequence queryString, Map<String, Object> params);
/**
* 分页查询实体
*
* @param queryString
* 查询语句
* @param pageIndex
* 当前页码,如果pageIndex<1则不分页,且返回pageSize条记录。
* @param pageSize
* 每页记录数,如果pageSize<1则返回所有记录。
* @param params
* 可选的查询参数
* @return 实体分页对象
*/
@SuppressWarnings("hiding")
<T> Pagination<T> findPagination(CharSequence queryString, int pageIndex, int pageSize, Object... params);
/**
* 分页查询实体
*
* @param queryString
* 查询语句
* @param params
* 可选的查询参数
* @param pageIndex
* 当前页码,如果pageIndex<2则不分页,且返回pageSize条记录。
* @param pageSize
* 每页记录数,如果pageSize<1则返回所有记录。
*
* @return 实体分页对象
*/
@SuppressWarnings("hiding")
<T> Pagination<T> findPagination(CharSequence queryString, Map<String, Object> params, int pageIndex, int pageSize);
/**
* 分页查询实体,自定义总条数查询语句,适合复杂的hql分页查询
*
* @param queryString
* 查询语句
* @param countString
* 查询记录总条数语句
* @param pageIndex
* 当前页码,如果pageIndex<1则不分页,且返回pageSize条记录。
* @param pageSize
* 每页记录数,如果pageSize<1则返回所有记录。
* @param params
* 可选的查询参数
* @return 实体分页对象
*/
@SuppressWarnings("hiding")
<T> Pagination<T> findPagination(CharSequence queryString, CharSequence countString, int pageIndex, int pageSize,
Object... params);
/**
* 分页查询实体,自定义总条数查询语句,适合复杂的hql分页查询
*
* @param queryString
* 查询语句
* @param countString
* 查询记录总条数语句
* @param params
* 可选的查询参数
* @param pageIndex
* 当前页码,如果pageIndex<2则不分页,且返回pageSize条记录。
* @param pageSize
* 每页记录数,如果pageSize<1则返回所有记录。
*
* @return 实体分页对象
*/
@SuppressWarnings("hiding")
<T> Pagination<T> findPagination(CharSequence queryString, CharSequence countString, Map<String, Object> params,
int pageIndex, int pageSize);
/**
* 分页查询实体,自定义总条数查询语句,适合复杂的sql分页查询
*
* @param queryString
* 查询语句
* @param countString
* 查询记录总条数语句
* @param params
* 可选的查询参数
* @param pageIndex
* 当前页码,如果pageIndex<2则不分页,且返回pageSize条记录。
* @param pageSize
* 每页记录数,如果pageSize<1则返回所有记录。
*
* @return 实体分页对象
*/
@SuppressWarnings("hiding")
public <T> Pagination<T> findSqlPagination(final CharSequence queryString, final CharSequence countString,
final Map<String, Object> params, int pageIndex, int pageSize);
/**
* 执行数据库更新操作
*
* @deprecated 用{@link #executeUpdate(String)}替换
* @param hql
*/
void execute(String hql);
/**
* 执行数据库更新操作
*
* @deprecated 用{@link #executeUpdate(HibernateHandler)}替换
* @param hql
*/
void execute(HibernateHandler handler);
/**
* 执行数据库更新操作
*
* @deprecated 用{@link #executeSqlUpdate(String)}替换
* @param sql
*/
void executeSql(String sql);
/**
* 执行数据库查询操作
*
* @param handler
* 处理器
* @return
* @throws Exception
*/
Object executeQuery(HibernateHandler handler);
/**
* 执行数据库更新操作
*
* @param sql
* @return 更新的记录条数
*/
int executeSqlUpdate(String sql);
/**
* 执行数据库更新操作
*
* @param hql
* @return 更新的记录条数
*/
int executeUpdate(String hql);
/**
* 执行数据库更新操作
*
* @param handler
* 处理器
* @return
* @throws Exception
*/
Object executeUpdate(HibernateHandler handler);
public T getById(Serializable id);
public T saveEntity(T o);
public T insert(T o);
public void save(List<T> list);
public void insert(List<T> list);
public void delete(List<T> list);
public void update(List<T> list);
public List<T> findByProperty(String name, Object value);
public List<T> findByProperty(Map<String, Object> conditionMap);
/**
*
* 查询实体列表
*
* @param queryString
* 查询语句
* @param maxResults
* 列表最大数
* @param params
* 可选的查询参数
* @return 实体列表
*/
public <V> List<V> findListByMax(CharSequence queryString, int maxResults, Object... params);
/**
*
* 查询实体列表
*
* @param queryString
* 查询语句
* @param maxResults
* 列表最大数
* @param params
* 可选的查询参数
* @return 实体列表
*/
public <V> List<V> findListByMax(CharSequence queryString, int maxResults, Map<String, Object> params);
}
BaseDaoImpl.java
- import java.io.Serializable;
- import java.lang.reflect.ParameterizedType;
- import java.lang.reflect.Type;
- import java.math.BigInteger;
- import java.text.ParseException;
- import java.text.SimpleDateFormat;
- import java.util.ArrayList;
- import java.util.Calendar;
- import java.util.Collection;
- import java.util.Date;
- import java.util.Iterator;
- import java.util.List;
- import java.util.Map;
- import javax.annotation.Resource;
- import org.hibernate.Query;
- import org.hibernate.SQLQuery;
- import org.hibernate.Session;
- import org.hibernate.SessionFactory;
- import org.hibernate.transform.Transformers;
- import org.springframework.stereotype.Repository;
- import com.xxx.finance.dao.BaseDao;
- import com.xxx.finance.utils.HibernateHandler;
- import com.xxx.finance.utils.ObjectUtil;
- import com.xxx.finance.utils.Pagination;
- /**
- * @author
- */
- @Repository
- public class BaseDaoImpl<T> implements BaseDao<T> {
- protected Class<T> entityClazz;
- protected SessionFactory sessionFactory;
- @SuppressWarnings("unchecked")
- public BaseDaoImpl() {
- Type type = getClass().getGenericSuperclass();
- if (type instanceof ParameterizedType) {
- this.entityClazz = (Class<T>) ((ParameterizedType) type).getActualTypeArguments()[0];
- } else {
- this.entityClazz = null;
- }
- }
- @Resource
- public void setSessionFactory(SessionFactory sessionFactory) {
- this.sessionFactory = sessionFactory;
- }
- protected Session getSession() {
- return sessionFactory.getCurrentSession();
- }
- @SuppressWarnings("unchecked")
- public Object save(Object entity) {
- return (T) getSession().save(entity);
- }
- public void delete(Object entity) {
- getSession().delete(entity);
- }
- public void update(Object entity) {
- getSession().update(entity);
- }
- public void saveOrUpdate(Object entity) {
- getSession().saveOrUpdate(entity);
- }
- public void saveAll(Collection<?> entities) {
- for (@SuppressWarnings("rawtypes")
- Iterator localIterator = entities.iterator(); localIterator.hasNext();) {
- Object entity = localIterator.next();
- getSession().save(entity);
- }
- }
- public void deleteAll(Collection<?> entities) {
- for (@SuppressWarnings("rawtypes")
- Iterator localIterator = entities.iterator(); localIterator.hasNext();) {
- Object entity = localIterator.next();
- getSession().delete(entity);
- }
- }
- public void updateAll(Collection<?> entities) {
- for (@SuppressWarnings("rawtypes")
- Iterator localIterator = entities.iterator(); localIterator.hasNext();) {
- Object entity = localIterator.next();
- getSession().update(entity);
- }
- }
- public void saveOrUpdateAll(Collection<?> entities) {
- for (@SuppressWarnings("rawtypes")
- Iterator localIterator = entities.iterator(); localIterator.hasNext();) {
- Object entity = localIterator.next();
- getSession().saveOrUpdate(entity);
- }
- }
- @SuppressWarnings({ "unchecked", "hiding" })
- public <T> T get(Class<T> entityClass, Serializable id) {
- return (T) getSession().get(entityClass, id);
- }
- @SuppressWarnings({ "unchecked", "rawtypes", "hiding" })
- public <T> T get(CharSequence queryString, Object... params) {
- Query qry = getSession().createQuery(queryString.toString());
- for (int i = 0; i < params.length; ++i) {
- qry.setParameter(i, params[i]);
- }
- List list = qry.setMaxResults(1).list();
- if (list.isEmpty())
- return null;
- return (T) list.get(0);
- }
- @SuppressWarnings({ "unchecked", "hiding" })
- public <T> T get(CharSequence queryString, Map<String, Object> params) {
- Query qry = getSession().createQuery(queryString.toString());
- setParameter(qry, params);
- @SuppressWarnings("rawtypes")
- List list = qry.setMaxResults(1).list();
- if (list.isEmpty())
- return null;
- return (T) list.get(0);
- }
- @SuppressWarnings({ "unchecked", "hiding" })
- public <T> List<T> findList(CharSequence queryString, Object... params) {
- Query query = getSession().createQuery(queryString.toString());
- for (int i = 0; i < params.length; ++i) {
- query.setParameter(i, params[i]);
- }
- return query.list();
- }
- @SuppressWarnings({ "unchecked", "hiding" })
- public <T> List<T> findList(CharSequence queryString, Map<String, Object> params) {
- Query query = getSession().createQuery(queryString.toString());
- setParameter(query, params);
- return query.list();
- }
- @SuppressWarnings({ "unchecked", "hiding" })
- public <T> Pagination<T> findPagination(CharSequence queryString, int pageIndex, int pageSize, Object... params) {
- Query query = getSession().createQuery(queryString.toString());
- if ((pageSize > 0) && (pageIndex > 0)) {
- query.setFirstResult((pageIndex < 2) ? 0 : (pageIndex - 1) * pageSize);
- query.setMaxResults(pageSize);
- }
- for (int i = 0; i < params.length; ++i) {
- query.setParameter(i, params[i]);
- }
- @SuppressWarnings("rawtypes")
- List items = query.list();
- long rowsCount = 0L;
- if ((pageSize > 0) && (pageIndex > 0)) {
- String hql = parseSelectCount(queryString.toString());
- rowsCount = ((Long) get(hql, params)).longValue();
- } else {
- rowsCount = items.size();
- }
- @SuppressWarnings("rawtypes")
- Pagination pagination = new Pagination(pageIndex, pageSize, rowsCount);
- pagination.setItems(items);
- return pagination;
- }
- @SuppressWarnings({ "unchecked", "hiding" })
- public <T> Pagination<T> findPagination(CharSequence queryString, Map<String, Object> params, int pageIndex,
- int pageSize) {
- Query query = getSession().createQuery(queryString.toString());
- if ((pageSize > 0) && (pageIndex > 0)) {
- query.setFirstResult((pageIndex < 2) ? 0 : (pageIndex - 1) * pageSize);
- query.setMaxResults(pageSize);
- }
- setParameter(query, params);
- @SuppressWarnings({ "rawtypes" })
- List items = query.list();
- long rowsCount = 0L;
- if ((pageSize > 0) && (pageIndex > 0)) {
- String hql = parseSelectCount(queryString.toString());
- rowsCount = ((Long) get(hql, params)).longValue();
- } else {
- rowsCount = items.size();
- }
- @SuppressWarnings("rawtypes")
- Pagination pagination = new Pagination(pageIndex, pageSize, rowsCount);
- pagination.setItems(items);
- return pagination;
- }
- @SuppressWarnings({ "unchecked", "hiding" })
- public <T> Pagination<T> findPagination(CharSequence queryString, CharSequence countString, int pageIndex,
- int pageSize, Object... params) {
- Query query = getSession().createQuery(queryString.toString());
- if ((pageSize > 0) && (pageIndex > 0)) {
- query.setFirstResult((pageIndex < 2) ? 0 : (pageIndex - 1) * pageSize);
- query.setMaxResults(pageSize);
- }
- for (int i = 0; i < params.length; ++i) {
- query.setParameter(i, params[i]);
- }
- @SuppressWarnings("rawtypes")
- List items = query.list();
- long rowsCount = 0L;
- if ((pageSize > 0) && (pageIndex > 0)) {
- rowsCount = ((Long) get(countString, params)).longValue();
- } else
- rowsCount = items.size();
- @SuppressWarnings("rawtypes")
- Pagination pagination = new Pagination(pageIndex, pageSize, rowsCount);
- pagination.setItems(items);
- return pagination;
- }
- @SuppressWarnings({ "unchecked", "hiding" })
- public <T> Pagination<T> findPagination(CharSequence queryString, CharSequence countString,
- Map<String, Object> params, int pageIndex, int pageSize) {
- Query query = getSession().createQuery(queryString.toString());
- if ((pageSize > 0) && (pageIndex > 0)) {
- query.setFirstResult((pageIndex < 2) ? 0 : (pageIndex - 1) * pageSize);
- query.setMaxResults(pageSize);
- }
- setParameter(query, params);
- @SuppressWarnings("rawtypes")
- List items = query.list();
- long rowsCount = 0L;
- if ((pageSize > 0) && (pageIndex > 0)) {
- rowsCount = ((Long) get(countString, params)).longValue();
- } else
- rowsCount = items.size();
- @SuppressWarnings("rawtypes")
- Pagination pagination = new Pagination(pageIndex, pageSize, rowsCount);
- pagination.setItems(items);
- return pagination;
- }
- @SuppressWarnings({ "serial", "unchecked", "hiding" })
- public <T> Pagination<T> findSqlPagination(CharSequence queryString, final CharSequence countString,
- final Map<String, Object> params, int pageIndex, int pageSize) {
- SQLQuery query = getSession().createSQLQuery(queryString.toString());
- query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
- if ((pageSize > 0) && (pageIndex > 0)) {
- query.setFirstResult((pageIndex < 2) ? 0 : (pageIndex - 1) * pageSize);
- query.setMaxResults(pageSize);
- }
- if ((params != null) && (!(params.isEmpty()))) {
- setParameter(query, params);
- }
- @SuppressWarnings("rawtypes")
- List items = query.list();
- BigInteger rowsCount = BigInteger.valueOf(0L);
- if ((pageSize > 0) && (pageIndex > 0)) {
- rowsCount = (BigInteger) executeQuery(new HibernateHandler() {
- public Object doInHibernate(Session session) {
- SQLQuery query = session.createSQLQuery(countString.toString());
- if ((params != null) && (!(params.isEmpty()))) {
- setParameter(query, params);
- }
- return query.uniqueResult();
- }
- });
- }
- @SuppressWarnings("rawtypes")
- Pagination pagination = new Pagination(pageIndex, pageSize, rowsCount.intValue());
- pagination.setItems(items);
- return pagination;
- }
- public Object executeQuery(HibernateHandler handler) {
- return handler.doInHibernate(getSession());
- }
- public void execute(String hql) {
- executeUpdate(hql);
- }
- public void execute(HibernateHandler handler) {
- executeUpdate(handler);
- }
- public void executeSql(String sql) {
- executeSqlUpdate(sql);
- }
- public int executeSqlUpdate(String sql) {
- return getSession().createSQLQuery(sql).executeUpdate();
- }
- public int executeUpdate(String hql) {
- return getSession().createQuery(hql).executeUpdate();
- }
- public Object executeUpdate(HibernateHandler handler) {
- return handler.doInHibernate(getSession());
- }
- protected Query setParameter(Query query, Map<String, Object> parameterMap) {
- for (@SuppressWarnings("rawtypes")
- Iterator iterator = parameterMap.keySet().iterator(); iterator.hasNext();) {
- String key = (String) iterator.next();
- query.setParameter(key, parameterMap.get(key));
- }
- return query;
- }
- protected boolean followWithWord(String s, String sub, int pos) {
- int i = 0;
- for (; (pos < s.length()) && (i < sub.length()); ++i) {
- if (s.charAt(pos) != sub.charAt(i))
- return false;
- ++pos;
- }
- if (i < sub.length()) {
- return false;
- }
- if (pos >= s.length()) {
- return true;
- }
- return (!(isAlpha(s.charAt(pos))));
- }
- protected String parseSelectCount(String queryString) {
- String hql = queryString.toLowerCase();
- int noBlankStart = 0;
- for (int len = hql.length(); noBlankStart < len; ++noBlankStart) {
- if (hql.charAt(noBlankStart) > ' ') {
- break;
- }
- }
- int pair = 0;
- if (!(followWithWord(hql, "select", noBlankStart))) {
- pair = 1;
- }
- int fromPos = -1;
- for (int i = noBlankStart; i < hql.length();) {
- if (followWithWord(hql, "select", i)) {
- ++pair;
- i += "select".length();
- } else if (followWithWord(hql, "from", i)) {
- --pair;
- if (pair == 0) {
- fromPos = i;
- break;
- }
- i += "from".length();
- } else {
- ++i;
- }
- }
- if (fromPos == -1) {
- throw new IllegalArgumentException("parse count sql error, check your sql/hql");
- }
- String countHql = "select count(*) " + queryString.substring(fromPos);
- return countHql;
- }
- protected boolean isAlpha(char c) {
- return ((c == '_') || (('0' <= c) && (c <= '9')) || (('a' <= c) && (c <= 'z')) || (('A' <= c) && (c <= 'Z')));
- }
- public void delete(Serializable id) {
- T entity = getById(id);
- delete(entity);
- }
- public void delete(List<T> entitys) {
- for (T entity : entitys) {
- delete(entity);
- }
- }
- public T getById(Serializable id) {
- if (id == null)
- return null;
- return (T) get(entityClazz, id);
- }
- @Override
- public T saveEntity(T o) {
- saveOrUpdate(o);
- return o;
- }
- @Override
- public void save(List<T> list) {
- saveOrUpdateAll(list);
- }
- @Override
- public T insert(T entity) {
- save(entity);
- return entity;
- }
- @Override
- public void insert(List<T> entitys) {
- for (T entity : entitys) {
- save(entity);
- }
- }
- @Override
- public void update(List<T> entitys) {
- for (T entity : entitys) {
- update(entity);
- }
- }
- @Override
- public List<T> findByProperty(String name, Object value) {
- String hql = "from " + entityClazz.getSimpleName() + " where " + name + "=? ";
- return findList(hql, value);
- }
- @Override
- public List<T> findByProperty(Map<String, Object> conditionMap) {
- StringBuilder hql = new StringBuilder();
- hql.append("from " + entityClazz.getSimpleName());
- if (!conditionMap.isEmpty()) {
- Iterator<String> it = conditionMap.keySet().iterator();
- String key = it.next();
- hql.append(" where " + key + "=:" + key);
- while (it.hasNext()) {
- key = it.next();
- hql.append(" and " + key + "=:" + key);
- }
- }
- return findList(hql.toString(), conditionMap);
- }
- @Override
- public <V> List<V> findListByMax(final CharSequence queryString, final int maxResults, final Object... params) {
- @SuppressWarnings({ "unchecked", "serial" })
- List<V> list = (List<V>) executeQuery(new HibernateHandler() {
- @Override
- public List<V> doInHibernate(Session paramSession) {
- try {
- Query query = paramSession.createQuery(queryString.toString());
- for (int i = 0; i < params.length; ++i) {
- query.setParameter(i, params[i]);
- }
- return query.setMaxResults(maxResults).list();
- } catch (RuntimeException re) {
- throw re;
- }
- }
- });
- return list;
- }
- @Override
- public <V> List<V> findListByMax(final CharSequence queryString, final int maxResults,
- final Map<String, Object> params) {
- @SuppressWarnings({ "unchecked", "serial" })
- List<V> list = (List<V>) executeQuery(new HibernateHandler() {
- @Override
- public List<V> doInHibernate(Session paramSession) {
- try {
- Query query = paramSession.createQuery(queryString.toString());
- for (Iterator<String> iterator = params.keySet().iterator(); iterator.hasNext();) {
- String key = iterator.next();
- query.setParameter(key, params.get(key));
- }
- return query.setMaxResults(maxResults).list();
- } catch (RuntimeException re) {
- throw re;
- }
- }
- });
- return list;
- }
- /**
- * HQL/SQL之数据操作命令(DML)拼接辅助类
- *
- * @author PanJun
- * @deprecated by fu.zhanghua
- *
- */
- public class DmlHelper {
- private ThreadLocal<Calendar> cal = new ThreadLocal<Calendar>() {
- @Override
- protected Calendar initialValue() {
- return Calendar.getInstance();
- }
- };
- /** HQL/SQL参数 */
- public final List<Object> paramList = new ArrayList<Object>();
- /** HQL/SQL语句 */
- public final StringBuilder dmlCmd = new StringBuilder();
- public DmlHelper() {
- }
- public DmlHelper(CharSequence dml, Object... params) {
- if (dml != null) {
- dmlCmd.append(dml);
- for (Object o : params) {
- paramList.add(o);
- }
- }
- }
- @Override
- public String toString() {
- return "dml=" + dmlCmd + ", params=" + paramList;
- }
- public DmlHelper append(CharSequence dmlPart, Object... params) {
- if (dmlPart != null) {
- dmlCmd.append(" ").append(dmlPart);
- for (Object o : params) {
- paramList.add(o);
- }
- }
- return this;
- }
- public DmlHelper addEqual(String fieldName, Object value, Object... nullVal) {
- if (value == null || fieldName == null) {
- return this;
- }
- if (value instanceof String) {
- value = value.toString().trim();
- if ("".equals(value)) {
- return this;
- }
- }
- for (Object NULL : nullVal) {
- if (NULL == value) {
- return this;
- }
- if (value.equals(NULL)) {
- return this;
- }
- }
- dmlCmd.append(" and ").append(fieldName).append("=? ");
- paramList.add(value);
- return this;
- }
- public DmlHelper addLikeAll(String name, String value) {
- if (null == value || null == name)
- return this;
- value = "%" + value.trim().toLowerCase() + "%";
- dmlCmd.append(" and lower(").append(name).append(") like ? ");
- paramList.add(value);
- return this;
- }
- /**
- * 清除时间里的时分秒,只留日期
- *
- * @param date
- * @return new date
- */
- private void clearTime(Calendar calendar) {
- int y = calendar.get(Calendar.YEAR);
- int m = calendar.get(Calendar.MONTH);
- int d = calendar.get(Calendar.DAY_OF_MONTH);
- calendar.clear();
- calendar.set(Calendar.YEAR, y);
- calendar.set(Calendar.MONTH, m);
- calendar.set(Calendar.DAY_OF_MONTH, d);
- }
- /**
- * 添加开始日期、结束日期(注意时分秒不记入查询条件)查询条件,包含开始日期和结束日期
- *
- * @param fieldName
- * hbm对象属性名称或字段名
- * @param minDay
- * 开始日期
- * @param maxDay
- * 结果日期
- */
- public DmlHelper addDayRange(String fieldName, Date minDay, Date maxDay) {
- Calendar calendar = cal.get();
- if (minDay != null) {
- calendar.setTime(minDay);
- clearTime(calendar);
- calendar.add(Calendar.SECOND, -1);
- dmlCmd.append(" and ").append(fieldName).append(">? ");
- paramList.add(calendar.getTime());
- }
- if (maxDay != null) {
- calendar.setTime(maxDay);
- clearTime(calendar);
- calendar.add(Calendar.DAY_OF_MONTH, 1);
- dmlCmd.append(" and ").append(fieldName).append("<? ");
- paramList.add(calendar.getTime());
- }
- return this;
- }
- /**
- * 添加开始时间、结束时间查询条件,包含开始时间和结束时间
- *
- * @param fieldName
- * hbm对象属性名称或字段名
- * @param minTime
- * 开始时间
- * @param maxTime
- * 结果时间
- */
- public DmlHelper addDayRange(String fieldName, String minTime, String maxTime) {
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
- Date start_ = null, end_ = null;
- if (ObjectUtil.hasText(minTime) && ObjectUtil.hasText(maxTime)) {
- try {
- start_ = sdf.parse(minTime);
- end_ = sdf.parse(maxTime);
- } catch (ParseException e) {
- }
- }
- return addTimeRange(fieldName, start_, end_);
- }
- /**
- * 添加开始时间、结束时间查询条件,包含开始时间和结束时间
- *
- * @param fieldName
- * hbm对象属性名称或字段名
- * @param minTime
- * 开始时间
- * @param maxTime
- * 结果时间
- */
- public DmlHelper addTimeRange(String fieldName, Date minTime, Date maxTime) {
- if (minTime != null) {
- dmlCmd.append(" and ").append(fieldName).append(">? ");
- paramList.add(minTime);
- }
- if (maxTime != null) {
- dmlCmd.append(" and ").append(fieldName).append("<? ");
- paramList.add(maxTime);
- }
- return this;
- }
- public <D> Pagination<D> findPagin(int pageIndex, int pageSize) {
- String hql = dmlCmd.toString();
- Object[] allParams = new Object[paramList.size()];
- int i = 0;
- for (Object o : paramList) {
- allParams[i++] = o;
- }
- return findPagination(hql, pageIndex, pageSize, allParams);
- }
- }
- }
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.math.BigInteger;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Repository;
import com.xxx.finance.dao.BaseDao;
import com.xxx.finance.utils.HibernateHandler;
import com.xxx.finance.utils.ObjectUtil;
import com.xxx.finance.utils.Pagination;
/**
* @author
*/
@Repository
public class BaseDaoImpl<T> implements BaseDao<T> {
protected Class<T> entityClazz;
protected SessionFactory sessionFactory;
@SuppressWarnings("unchecked")
public BaseDaoImpl() {
Type type = getClass().getGenericSuperclass();
if (type instanceof ParameterizedType) {
this.entityClazz = (Class<T>) ((ParameterizedType) type).getActualTypeArguments()[0];
} else {
this.entityClazz = null;
}
}
@Resource
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
protected Session getSession() {
return sessionFactory.getCurrentSession();
}
@SuppressWarnings("unchecked")
public Object save(Object entity) {
return (T) getSession().save(entity);
}
public void delete(Object entity) {
getSession().delete(entity);
}
public void update(Object entity) {
getSession().update(entity);
}
public void saveOrUpdate(Object entity) {
getSession().saveOrUpdate(entity);
}
public void saveAll(Collection<?> entities) {
for (@SuppressWarnings("rawtypes")
Iterator localIterator = entities.iterator(); localIterator.hasNext();) {
Object entity = localIterator.next();
getSession().save(entity);
}
}
public void deleteAll(Collection<?> entities) {
for (@SuppressWarnings("rawtypes")
Iterator localIterator = entities.iterator(); localIterator.hasNext();) {
Object entity = localIterator.next();
getSession().delete(entity);
}
}
public void updateAll(Collection<?> entities) {
for (@SuppressWarnings("rawtypes")
Iterator localIterator = entities.iterator(); localIterator.hasNext();) {
Object entity = localIterator.next();
getSession().update(entity);
}
}
public void saveOrUpdateAll(Collection<?> entities) {
for (@SuppressWarnings("rawtypes")
Iterator localIterator = entities.iterator(); localIterator.hasNext();) {
Object entity = localIterator.next();
getSession().saveOrUpdate(entity);
}
}
@SuppressWarnings({ "unchecked", "hiding" })
public <T> T get(Class<T> entityClass, Serializable id) {
return (T) getSession().get(entityClass, id);
}
@SuppressWarnings({ "unchecked", "rawtypes", "hiding" })
public <T> T get(CharSequence queryString, Object... params) {
Query qry = getSession().createQuery(queryString.toString());
for (int i = 0; i < params.length; ++i) {
qry.setParameter(i, params[i]);
}
List list = qry.setMaxResults(1).list();
if (list.isEmpty())
return null;
return (T) list.get(0);
}
@SuppressWarnings({ "unchecked", "hiding" })
public <T> T get(CharSequence queryString, Map<String, Object> params) {
Query qry = getSession().createQuery(queryString.toString());
setParameter(qry, params);
@SuppressWarnings("rawtypes")
List list = qry.setMaxResults(1).list();
if (list.isEmpty())
return null;
return (T) list.get(0);
}
@SuppressWarnings({ "unchecked", "hiding" })
public <T> List<T> findList(CharSequence queryString, Object... params) {
Query query = getSession().createQuery(queryString.toString());
for (int i = 0; i < params.length; ++i) {
query.setParameter(i, params[i]);
}
return query.list();
}
@SuppressWarnings({ "unchecked", "hiding" })
public <T> List<T> findList(CharSequence queryString, Map<String, Object> params) {
Query query = getSession().createQuery(queryString.toString());
setParameter(query, params);
return query.list();
}
@SuppressWarnings({ "unchecked", "hiding" })
public <T> Pagination<T> findPagination(CharSequence queryString, int pageIndex, int pageSize, Object... params) {
Query query = getSession().createQuery(queryString.toString());
if ((pageSize > 0) && (pageIndex > 0)) {
query.setFirstResult((pageIndex < 2) ? 0 : (pageIndex - 1) * pageSize);
query.setMaxResults(pageSize);
}
for (int i = 0; i < params.length; ++i) {
query.setParameter(i, params[i]);
}
@SuppressWarnings("rawtypes")
List items = query.list();
long rowsCount = 0L;
if ((pageSize > 0) && (pageIndex > 0)) {
String hql = parseSelectCount(queryString.toString());
rowsCount = ((Long) get(hql, params)).longValue();
} else {
rowsCount = items.size();
}
@SuppressWarnings("rawtypes")
Pagination pagination = new Pagination(pageIndex, pageSize, rowsCount);
pagination.setItems(items);
return pagination;
}
@SuppressWarnings({ "unchecked", "hiding" })
public <T> Pagination<T> findPagination(CharSequence queryString, Map<String, Object> params, int pageIndex,
int pageSize) {
Query query = getSession().createQuery(queryString.toString());
if ((pageSize > 0) && (pageIndex > 0)) {
query.setFirstResult((pageIndex < 2) ? 0 : (pageIndex - 1) * pageSize);
query.setMaxResults(pageSize);
}
setParameter(query, params);
@SuppressWarnings({ "rawtypes" })
List items = query.list();
long rowsCount = 0L;
if ((pageSize > 0) && (pageIndex > 0)) {
String hql = parseSelectCount(queryString.toString());
rowsCount = ((Long) get(hql, params)).longValue();
} else {
rowsCount = items.size();
}
@SuppressWarnings("rawtypes")
Pagination pagination = new Pagination(pageIndex, pageSize, rowsCount);
pagination.setItems(items);
return pagination;
}
@SuppressWarnings({ "unchecked", "hiding" })
public <T> Pagination<T> findPagination(CharSequence queryString, CharSequence countString, int pageIndex,
int pageSize, Object... params) {
Query query = getSession().createQuery(queryString.toString());
if ((pageSize > 0) && (pageIndex > 0)) {
query.setFirstResult((pageIndex < 2) ? 0 : (pageIndex - 1) * pageSize);
query.setMaxResults(pageSize);
}
for (int i = 0; i < params.length; ++i) {
query.setParameter(i, params[i]);
}
@SuppressWarnings("rawtypes")
List items = query.list();
long rowsCount = 0L;
if ((pageSize > 0) && (pageIndex > 0)) {
rowsCount = ((Long) get(countString, params)).longValue();
} else
rowsCount = items.size();
@SuppressWarnings("rawtypes")
Pagination pagination = new Pagination(pageIndex, pageSize, rowsCount);
pagination.setItems(items);
return pagination;
}
@SuppressWarnings({ "unchecked", "hiding" })
public <T> Pagination<T> findPagination(CharSequence queryString, CharSequence countString,
Map<String, Object> params, int pageIndex, int pageSize) {
Query query = getSession().createQuery(queryString.toString());
if ((pageSize > 0) && (pageIndex > 0)) {
query.setFirstResult((pageIndex < 2) ? 0 : (pageIndex - 1) * pageSize);
query.setMaxResults(pageSize);
}
setParameter(query, params);
@SuppressWarnings("rawtypes")
List items = query.list();
long rowsCount = 0L;
if ((pageSize > 0) && (pageIndex > 0)) {
rowsCount = ((Long) get(countString, params)).longValue();
} else
rowsCount = items.size();
@SuppressWarnings("rawtypes")
Pagination pagination = new Pagination(pageIndex, pageSize, rowsCount);
pagination.setItems(items);
return pagination;
}
@SuppressWarnings({ "serial", "unchecked", "hiding" })
public <T> Pagination<T> findSqlPagination(CharSequence queryString, final CharSequence countString,
final Map<String, Object> params, int pageIndex, int pageSize) {
SQLQuery query = getSession().createSQLQuery(queryString.toString());
query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
if ((pageSize > 0) && (pageIndex > 0)) {
query.setFirstResult((pageIndex < 2) ? 0 : (pageIndex - 1) * pageSize);
query.setMaxResults(pageSize);
}
if ((params != null) && (!(params.isEmpty()))) {
setParameter(query, params);
}
@SuppressWarnings("rawtypes")
List items = query.list();
BigInteger rowsCount = BigInteger.valueOf(0L);
if ((pageSize > 0) && (pageIndex > 0)) {
rowsCount = (BigInteger) executeQuery(new HibernateHandler() {
public Object doInHibernate(Session session) {
SQLQuery query = session.createSQLQuery(countString.toString());
if ((params != null) && (!(params.isEmpty()))) {
setParameter(query, params);
}
return query.uniqueResult();
}
});
}
@SuppressWarnings("rawtypes")
Pagination pagination = new Pagination(pageIndex, pageSize, rowsCount.intValue());
pagination.setItems(items);
return pagination;
}
public Object executeQuery(HibernateHandler handler) {
return handler.doInHibernate(getSession());
}
public void execute(String hql) {
executeUpdate(hql);
}
public void execute(HibernateHandler handler) {
executeUpdate(handler);
}
public void executeSql(String sql) {
executeSqlUpdate(sql);
}
public int executeSqlUpdate(String sql) {
return getSession().createSQLQuery(sql).executeUpdate();
}
public int executeUpdate(String hql) {
return getSession().createQuery(hql).executeUpdate();
}
public Object executeUpdate(HibernateHandler handler) {
return handler.doInHibernate(getSession());
}
protected Query setParameter(Query query, Map<String, Object> parameterMap) {
for (@SuppressWarnings("rawtypes")
Iterator iterator = parameterMap.keySet().iterator(); iterator.hasNext();) {
String key = (String) iterator.next();
query.setParameter(key, parameterMap.get(key));
}
return query;
}
protected boolean followWithWord(String s, String sub, int pos) {
int i = 0;
for (; (pos < s.length()) && (i < sub.length()); ++i) {
if (s.charAt(pos) != sub.charAt(i))
return false;
++pos;
}
if (i < sub.length()) {
return false;
}
if (pos >= s.length()) {
return true;
}
return (!(isAlpha(s.charAt(pos))));
}
protected String parseSelectCount(String queryString) {
String hql = queryString.toLowerCase();
int noBlankStart = 0;
for (int len = hql.length(); noBlankStart < len; ++noBlankStart) {
if (hql.charAt(noBlankStart) > ' ') {
break;
}
}
int pair = 0;
if (!(followWithWord(hql, "select", noBlankStart))) {
pair = 1;
}
int fromPos = -1;
for (int i = noBlankStart; i < hql.length();) {
if (followWithWord(hql, "select", i)) {
++pair;
i += "select".length();
} else if (followWithWord(hql, "from", i)) {
--pair;
if (pair == 0) {
fromPos = i;
break;
}
i += "from".length();
} else {
++i;
}
}
if (fromPos == -1) {
throw new IllegalArgumentException("parse count sql error, check your sql/hql");
}
String countHql = "select count(*) " + queryString.substring(fromPos);
return countHql;
}
protected boolean isAlpha(char c) {
return ((c == '_') || (('0' <= c) && (c <= '9')) || (('a' <= c) && (c <= 'z')) || (('A' <= c) && (c <= 'Z')));
}
public void delete(Serializable id) {
T entity = getById(id);
delete(entity);
}
public void delete(List<T> entitys) {
for (T entity : entitys) {
delete(entity);
}
}
public T getById(Serializable id) {
if (id == null)
return null;
return (T) get(entityClazz, id);
}
@Override
public T saveEntity(T o) {
saveOrUpdate(o);
return o;
}
@Override
public void save(List<T> list) {
saveOrUpdateAll(list);
}
@Override
public T insert(T entity) {
save(entity);
return entity;
}
@Override
public void insert(List<T> entitys) {
for (T entity : entitys) {
save(entity);
}
}
@Override
public void update(List<T> entitys) {
for (T entity : entitys) {
update(entity);
}
}
@Override
public List<T> findByProperty(String name, Object value) {
String hql = "from " + entityClazz.getSimpleName() + " where " + name + "=? ";
return findList(hql, value);
}
@Override
public List<T> findByProperty(Map<String, Object> conditionMap) {
StringBuilder hql = new StringBuilder();
hql.append("from " + entityClazz.getSimpleName());
if (!conditionMap.isEmpty()) {
Iterator<String> it = conditionMap.keySet().iterator();
String key = it.next();
hql.append(" where " + key + "=:" + key);
while (it.hasNext()) {
key = it.next();
hql.append(" and " + key + "=:" + key);
}
}
return findList(hql.toString(), conditionMap);
}
@Override
public <V> List<V> findListByMax(final CharSequence queryString, final int maxResults, final Object... params) {
@SuppressWarnings({ "unchecked", "serial" })
List<V> list = (List<V>) executeQuery(new HibernateHandler() {
@Override
public List<V> doInHibernate(Session paramSession) {
try {
Query query = paramSession.createQuery(queryString.toString());
for (int i = 0; i < params.length; ++i) {
query.setParameter(i, params[i]);
}
return query.setMaxResults(maxResults).list();
} catch (RuntimeException re) {
throw re;
}
}
});
return list;
}
@Override
public <V> List<V> findListByMax(final CharSequence queryString, final int maxResults,
final Map<String, Object> params) {
@SuppressWarnings({ "unchecked", "serial" })
List<V> list = (List<V>) executeQuery(new HibernateHandler() {
@Override
public List<V> doInHibernate(Session paramSession) {
try {
Query query = paramSession.createQuery(queryString.toString());
for (Iterator<String> iterator = params.keySet().iterator(); iterator.hasNext();) {
String key = iterator.next();
query.setParameter(key, params.get(key));
}
return query.setMaxResults(maxResults).list();
} catch (RuntimeException re) {
throw re;
}
}
});
return list;
}
/**
* HQL/SQL之数据操作命令(DML)拼接辅助类
*
* @author PanJun
* @deprecated by fu.zhanghua
*
*/
public class DmlHelper {
private ThreadLocal<Calendar> cal = new ThreadLocal<Calendar>() {
@Override
protected Calendar initialValue() {
return Calendar.getInstance();
}
};
/** HQL/SQL参数 */
public final List<Object> paramList = new ArrayList<Object>();
/** HQL/SQL语句 */
public final StringBuilder dmlCmd = new StringBuilder();
public DmlHelper() {
}
public DmlHelper(CharSequence dml, Object... params) {
if (dml != null) {
dmlCmd.append(dml);
for (Object o : params) {
paramList.add(o);
}
}
}
@Override
public String toString() {
return "dml=" + dmlCmd + ", params=" + paramList;
}
public DmlHelper append(CharSequence dmlPart, Object... params) {
if (dmlPart != null) {
dmlCmd.append(" ").append(dmlPart);
for (Object o : params) {
paramList.add(o);
}
}
return this;
}
public DmlHelper addEqual(String fieldName, Object value, Object... nullVal) {
if (value == null || fieldName == null) {
return this;
}
if (value instanceof String) {
value = value.toString().trim();
if ("".equals(value)) {
return this;
}
}
for (Object NULL : nullVal) {
if (NULL == value) {
return this;
}
if (value.equals(NULL)) {
return this;
}
}
dmlCmd.append(" and ").append(fieldName).append("=? ");
paramList.add(value);
return this;
}
public DmlHelper addLikeAll(String name, String value) {
if (null == value || null == name)
return this;
value = "%" + value.trim().toLowerCase() + "%";
dmlCmd.append(" and lower(").append(name).append(") like ? ");
paramList.add(value);
return this;
}
/**
* 清除时间里的时分秒,只留日期
*
* @param date
* @return new date
*/
private void clearTime(Calendar calendar) {
int y = calendar.get(Calendar.YEAR);
int m = calendar.get(Calendar.MONTH);
int d = calendar.get(Calendar.DAY_OF_MONTH);
calendar.clear();
calendar.set(Calendar.YEAR, y);
calendar.set(Calendar.MONTH, m);
calendar.set(Calendar.DAY_OF_MONTH, d);
}
/**
* 添加开始日期、结束日期(注意时分秒不记入查询条件)查询条件,包含开始日期和结束日期
*
* @param fieldName
* hbm对象属性名称或字段名
* @param minDay
* 开始日期
* @param maxDay
* 结果日期
*/
public DmlHelper addDayRange(String fieldName, Date minDay, Date maxDay) {
Calendar calendar = cal.get();
if (minDay != null) {
calendar.setTime(minDay);
clearTime(calendar);
calendar.add(Calendar.SECOND, -1);
dmlCmd.append(" and ").append(fieldName).append(">? ");
paramList.add(calendar.getTime());
}
if (maxDay != null) {
calendar.setTime(maxDay);
clearTime(calendar);
calendar.add(Calendar.DAY_OF_MONTH, 1);
dmlCmd.append(" and ").append(fieldName).append("<? ");
paramList.add(calendar.getTime());
}
return this;
}
/**
* 添加开始时间、结束时间查询条件,包含开始时间和结束时间
*
* @param fieldName
* hbm对象属性名称或字段名
* @param minTime
* 开始时间
* @param maxTime
* 结果时间
*/
public DmlHelper addDayRange(String fieldName, String minTime, String maxTime) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date start_ = null, end_ = null;
if (ObjectUtil.hasText(minTime) && ObjectUtil.hasText(maxTime)) {
try {
start_ = sdf.parse(minTime);
end_ = sdf.parse(maxTime);
} catch (ParseException e) {
}
}
return addTimeRange(fieldName, start_, end_);
}
/**
* 添加开始时间、结束时间查询条件,包含开始时间和结束时间
*
* @param fieldName
* hbm对象属性名称或字段名
* @param minTime
* 开始时间
* @param maxTime
* 结果时间
*/
public DmlHelper addTimeRange(String fieldName, Date minTime, Date maxTime) {
if (minTime != null) {
dmlCmd.append(" and ").append(fieldName).append(">? ");
paramList.add(minTime);
}
if (maxTime != null) {
dmlCmd.append(" and ").append(fieldName).append("<? ");
paramList.add(maxTime);
}
return this;
}
public <D> Pagination<D> findPagin(int pageIndex, int pageSize) {
String hql = dmlCmd.toString();
Object[] allParams = new Object[paramList.size()];
int i = 0;
for (Object o : paramList) {
allParams[i++] = o;
}
return findPagination(hql, pageIndex, pageSize, allParams);
}
}
}
HibernateHandler.java
- import java.io.Serializable;
- import org.hibernate.Session;
- public abstract interface HibernateHandler extends Serializable {
- public abstract Object doInHibernate(Session paramSession);
- }
import java.io.Serializable;
import org.hibernate.Session;
public abstract interface HibernateHandler extends Serializable {
public abstract Object doInHibernate(Session paramSession);
}
Pagination.java
- import java.io.Serializable;
- import java.util.List;
- /**
- * 数据分页类
- *
- * @author GST
- * @version 1.0, 2006-12-30
- */
- public class Pagination<T> implements Serializable {
- private static final long serialVersionUID = -5884976706259160221L;
- /**
- * 上一页
- */
- private long preIndex;
- /**
- * 当前页
- */
- private long curIndex;
- /**
- * 下一页
- */
- private long nextIndex;
- /**
- * 每页条数
- */
- private long pageSize;
- /**
- * 总条数
- */
- private long rowsCount;
- public void setPreIndex(long preIndex) {
- this.preIndex = preIndex;
- }
- public void setCurIndex(long curIndex) {
- this.curIndex = curIndex;
- }
- public void setNextIndex(long nextIndex) {
- this.nextIndex = nextIndex;
- }
- public void setPageSize(long pageSize) {
- this.pageSize = pageSize;
- }
- /**
- * 总页数
- */
- private long pagesCount;
- /**
- * 对象列表
- */
- private List<T> items;
- /**
- *
- * 分页类构建函数
- *
- */
- public Pagination() {
- updateInfo(0, 0, 0);
- }
- /**
- *
- * 分页类构建函数
- *
- * @param pageIndex
- * 当前页码
- * @param pageSize
- * 每页记录数
- */
- public Pagination(long pageIndex, long pageSize) {
- updateInfo(pageIndex, pageSize, 0);
- }
- /**
- * 分页类构建函数
- *
- * @param pageIndex
- * 当前页码
- * @param pageSize
- * 每页记录数
- * @param rowsCount
- * 记录总数
- */
- public Pagination(long pageIndex, long pageSize, long rowsCount) {
- updateInfo(pageIndex, pageSize, rowsCount);
- }
- /**
- * 获取当前面记录
- *
- * @return
- */
- public List<T> getItems() {
- return items;
- }
- /**
- * 设置当前页记录
- *
- * @param items
- */
- public void setItems(List<T> items) {
- this.items = items;
- }
- /**
- * 获取当前页码
- *
- * @return
- */
- public long getCurIndex() {
- return curIndex;
- }
- /**
- * 获取下一页码
- *
- * @return
- */
- public long getNextIndex() {
- return nextIndex;
- }
- /**
- * 获取总页数
- *
- * @return
- */
- public long getPagesCount() {
- return pagesCount;
- }
- /**
- * 获取每页记录数
- *
- * @return
- */
- public long getPageSize() {
- return pageSize;
- }
- /**
- * 获取上一页码
- *
- * @return
- */
- public long getPreIndex() {
- return preIndex;
- }
- /**
- * 获取总记录数
- *
- * @return
- */
- public long getRowsCount() {
- return rowsCount;
- }
- /**
- * 获取首页码
- *
- * @return
- */
- public long getFirstIndex() {
- return 1;
- }
- /**
- * 获取末页码
- *
- * @return
- */
- public long getLastIndex() {
- return pagesCount;
- }
- private void updateInfo(long pageIndex, long pageSize, long rowsCount) {
- if (pageSize > 0) {
- this.curIndex = pageIndex;
- this.rowsCount = rowsCount;
- this.pageSize = pageSize;
- // 确定页数
- pagesCount = (rowsCount + pageSize - 1) / pageSize;
- // 确定当前页码
- if (curIndex <= 0)
- curIndex = 1;
- if (curIndex > pagesCount)
- curIndex = pagesCount;
- // 确定下一页码
- nextIndex = curIndex + 1;
- if (nextIndex > pagesCount)
- nextIndex = pagesCount;
- // 确定上一页码
- preIndex = curIndex - 1;
- if (preIndex <= 0)
- preIndex = 1;
- } else {
- this.preIndex = 1;
- this.curIndex = 1;
- this.nextIndex = 1;
- this.pageSize = 0;
- this.pagesCount = 1;
- }
- }
- /**
- * 设置总记录数
- *
- * @param rowsCount
- */
- public void setRowsCount(long rowsCount) {
- updateInfo(curIndex, pageSize, rowsCount);
- }
- /**
- * 设置总页数
- *
- * @param pagesCount
- */
- public void setPagesCount(long pagesCount) {
- this.pagesCount = pagesCount;
- }
- }
import java.io.Serializable;
import java.util.List;
/**
* 数据分页类
*
* @author GST
* @version 1.0, 2006-12-30
*/
public class Pagination<T> implements Serializable {
private static final long serialVersionUID = -5884976706259160221L;
/**
* 上一页
*/
private long preIndex;
/**
* 当前页
*/
private long curIndex;
/**
* 下一页
*/
private long nextIndex;
/**
* 每页条数
*/
private long pageSize;
/**
* 总条数
*/
private long rowsCount;
public void setPreIndex(long preIndex) {
this.preIndex = preIndex;
}
public void setCurIndex(long curIndex) {
this.curIndex = curIndex;
}
public void setNextIndex(long nextIndex) {
this.nextIndex = nextIndex;
}
public void setPageSize(long pageSize) {
this.pageSize = pageSize;
}
/**
* 总页数
*/
private long pagesCount;
/**
* 对象列表
*/
private List<T> items;
/**
*
* 分页类构建函数
*
*/
public Pagination() {
updateInfo(0, 0, 0);
}
/**
*
* 分页类构建函数
*
* @param pageIndex
* 当前页码
* @param pageSize
* 每页记录数
*/
public Pagination(long pageIndex, long pageSize) {
updateInfo(pageIndex, pageSize, 0);
}
/**
* 分页类构建函数
*
* @param pageIndex
* 当前页码
* @param pageSize
* 每页记录数
* @param rowsCount
* 记录总数
*/
public Pagination(long pageIndex, long pageSize, long rowsCount) {
updateInfo(pageIndex, pageSize, rowsCount);
}
/**
* 获取当前面记录
*
* @return
*/
public List<T> getItems() {
return items;
}
/**
* 设置当前页记录
*
* @param items
*/
public void setItems(List<T> items) {
this.items = items;
}
/**
* 获取当前页码
*
* @return
*/
public long getCurIndex() {
return curIndex;
}
/**
* 获取下一页码
*
* @return
*/
public long getNextIndex() {
return nextIndex;
}
/**
* 获取总页数
*
* @return
*/
public long getPagesCount() {
return pagesCount;
}
/**
* 获取每页记录数
*
* @return
*/
public long getPageSize() {
return pageSize;
}
/**
* 获取上一页码
*
* @return
*/
public long getPreIndex() {
return preIndex;
}
/**
* 获取总记录数
*
* @return
*/
public long getRowsCount() {
return rowsCount;
}
/**
* 获取首页码
*
* @return
*/
public long getFirstIndex() {
return 1;
}
/**
* 获取末页码
*
* @return
*/
public long getLastIndex() {
return pagesCount;
}
private void updateInfo(long pageIndex, long pageSize, long rowsCount) {
if (pageSize > 0) {
this.curIndex = pageIndex;
this.rowsCount = rowsCount;
this.pageSize = pageSize;
// 确定页数
pagesCount = (rowsCount + pageSize - 1) / pageSize;
// 确定当前页码
if (curIndex <= 0)
curIndex = 1;
if (curIndex > pagesCount)
curIndex = pagesCount;
// 确定下一页码
nextIndex = curIndex + 1;
if (nextIndex > pagesCount)
nextIndex = pagesCount;
// 确定上一页码
preIndex = curIndex - 1;
if (preIndex <= 0)
preIndex = 1;
} else {
this.preIndex = 1;
this.curIndex = 1;
this.nextIndex = 1;
this.pageSize = 0;
this.pagesCount = 1;
}
}
/**
* 设置总记录数
*
* @param rowsCount
*/
public void setRowsCount(long rowsCount) {
updateInfo(curIndex, pageSize, rowsCount);
}
/**
* 设置总页数
*
* @param pagesCount
*/
public void setPagesCount(long pagesCount) {
this.pagesCount = pagesCount;
}
}
ObjectUtil.java
- import java.lang.reflect.InvocationTargetException;
- import java.lang.reflect.Method;
- import java.lang.reflect.ParameterizedType;
- import java.lang.reflect.Type;
- import java.util.ArrayList;
- import java.util.Date;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- /**
- * @author Administrator
- * @date 2013-4-27 上午10:51:14
- * @since 1.0
- */
- public class ObjectUtil {
- /**
- * <p>
- * 把原对象的属性值拷贝到目标对象,并返回目标对象.<b>拷贝空值</b>.
- * </p>
- *
- * @param source
- * 数据来源对象
- * @param target
- * 目标对象
- * @return 目标对象
- */
- public static <T> T copyPropVal(Object source, T target) {
- return copyPropVal(source, target, true);
- }
- /**
- * 把原对象的属性值拷贝到目标对象,并返回目标对象;不处理复合属性;<b>不拷贝空值</b>
- *
- * @param <T>
- * @param source
- * @param target
- * @return 目标对象
- */
- public static <T> T copyNotNullPropVal(Object source, T target) {
- return copyPropVal(source, target, false);
- }
- private static Object callGetter(Object o, List<Method> getterList) {
- if (getterList == null || o == null)
- return null;
- for (Method m : getterList) {
- if (!m.getReturnType().equals(void.class) && m.getParameterTypes().length == 0) {
- try {
- return m.invoke(o);
- } catch (Exception e) {
- }
- }
- }
- return null;
- }
- private static void callSetter(Object o, Object val, List<Method> setterList) {
- if (setterList == null || o == null)
- return;
- for (Method m : setterList) {
- if (m.getReturnType().equals(void.class) && m.getParameterTypes().length == 1) {
- try {
- m.invoke(o, val);
- return;
- } catch (Exception e) {
- }
- }
- }
- }
- /**
- * 见prepareToSave,空值默认<b>不</b>覆盖
- *
- * @param savingEntity
- * 要保存到数据库的实体对象
- * @param valueEntity
- * 数值实体
- * @param userId
- * 当前用户ID
- * @return 处理以后的参数savingEntity
- */
- public static <T> T prepareToSave(T savingEntity, Object valueEntity, String userId) {
- return prepareToSave(savingEntity, valueEntity, userId, false);
- }
- /**
- * 在保存savingEntity实体之前,完成对savingEntity字段值的设置操作,具体如下:<br>
- * 1)设置savingEntity的通用字段getDisabled(isDisabled), getCreateTime,
- * getCreatedBy,setCreateTime,setCreateBy,setUpdateTime,setUpdateBy 2)拷贝
- * 数值实体valueEntity 所有属性值到savingEntity相应属性<br>
- * 本方法返回待保存的实体
- *
- * @param <T>
- * @param savingEntity
- * 要保存到数据库的实体对象
- * @param valueEntity
- * 数值实体
- * @param userId
- * 当前用户ID
- * @param copyNull
- * 是否拷贝空值
- * @return 处理以后的参数savingEntity
- */
- public static <T> T prepareToSave(T savingEntity, Object valueEntity, String userId, boolean copyNull) {
- if (savingEntity == null)
- return savingEntity;
- HashMap<String, List<Method>> methodMap = new HashMap<String, List<Method>>();
- for (Method m : savingEntity.getClass().getMethods()) {
- List<Method> list = methodMap.get(m.getName());
- if (list == null) {
- list = new ArrayList<Method>();
- methodMap.put(m.getName(), list);
- }
- list.add(m);
- }
- Object createTime = callGetter(savingEntity, methodMap.get("getCreateTime"));
- Object createBy = callGetter(savingEntity, methodMap.get("getCreateBy"));
- copyPropVal(valueEntity, savingEntity, copyNull);
- Date now = new Date();
- if (createTime == null)
- createTime = now;
- if (createBy == null)
- createBy = userId;
- // ~~exam or ERP~~
- Object creationDate = callGetter(savingEntity, methodMap.get("getCreationDate"));
- Object createdBy = callGetter(savingEntity, methodMap.get("getCreatedBy"));
- if (createdBy == null)
- createdBy = userId;
- if (creationDate == null)
- creationDate = now;
- // ~~exam or ERP~~
- Object disabled = callGetter(savingEntity, methodMap.get("getDisabled"));
- if (disabled == null)
- disabled = callGetter(savingEntity, methodMap.get("isDisabled"));
- if (disabled == null)
- callSetter(savingEntity, false, methodMap.get("setDisabled"));
- callSetter(savingEntity, createBy, methodMap.get("setCreateBy"));
- callSetter(savingEntity, createTime, methodMap.get("setCreateTime"));
- callSetter(savingEntity, now, methodMap.get("setUpdateTime"));
- callSetter(savingEntity, userId, methodMap.get("setUpdateBy"));
- // ~~exam or ERP~~
- callSetter(savingEntity, createdBy, methodMap.get("setCreatedBy"));
- callSetter(savingEntity, creationDate, methodMap.get("setCreationDate"));
- callSetter(savingEntity, now, methodMap.get("setLastUpdateDate"));
- callSetter(savingEntity, userId, methodMap.get("setLastUpdatedBy"));
- callSetter(savingEntity, userId, methodMap.get("setLastUpdateLogin"));
- // ~~exam or ERP~~
- return savingEntity;
- }
- private static boolean isZteClass(Type type) {
- if (!(type instanceof Class))
- return false;
- DataObjectDescriptor annotation = ((Class<?>) type).getAnnotation(DataObjectDescriptor.class);
- return annotation != null;
- }
- @SuppressWarnings({ "unchecked", "rawtypes" })
- private static Map<?, ?> makeTargetMap(Map<?, ?> source, Type keyType, Type valType, boolean copyNull)
- throws Exception {
- if (!(keyType instanceof Class))
- throw new UnsupportedOperationException("makeTargetMap " + keyType);
- Class<?> keyClzz = (Class<?>) keyType;
- Map result = new HashMap();
- for (Object k : source.keySet()) {
- Object srcVal = source.get(k);
- Object value = srcVal;
- Object key = k;
- if (isZteClass(keyClzz))
- key = copyNotNullPropVal(k, keyClzz.newInstance());
- if (isZteClass(valType)) {
- value = copyPropVal(srcVal, ((Class<?>) valType).newInstance(), copyNull);
- } else if (checkCopyAsList(srcVal, valType)) {
- Type actualType = ((ParameterizedType) valType).getActualTypeArguments()[0];
- value = makeTargetList((List<?>) srcVal, (Class<?>) actualType, copyNull);
- } else if (checkCopyAsMap(srcVal, valType)) {
- ParameterizedType prmType = (ParameterizedType) valType;
- Type subKeyType = prmType.getActualTypeArguments()[0];
- Type subValType = prmType.getActualTypeArguments()[1];
- value = makeTargetMap((Map<?, ?>) srcVal, subKeyType, subValType, copyNull);
- }
- result.put(key, value);
- }
- return result;
- }
- /**
- * 把原对象的属性值拷贝到目标对象,并返回目标对象;不处理复合属性,可控制是否拷贝空值
- *
- * @param <T>
- * @param source
- * @param target
- * @param copyNull
- * 是否拷贝空值
- * @return 目标对象
- */
- public static <T> T copyPropVal(Object source, T target, boolean copyNull) {
- if (source == null || target == null)
- return target;
- Map<String, Method> getterMap = new HashMap<String, Method>();
- for (Method m : source.getClass().getMethods()) {
- if (m.getParameterTypes().length > 0)
- continue;
- String name = m.getName();
- if (name.startsWith("get") && name.length() > 3) {
- name = name.substring(3);
- getterMap.put(name, m);
- } else if (name.startsWith("is") && name.length() > 2 && m.getReturnType() == boolean.class) {
- name = name.substring(2);
- getterMap.put(name, m);
- }
- }
- for (Method setter : target.getClass().getMethods()) {
- String name = setter.getName();
- Type[] paramTypes = setter.getGenericParameterTypes();
- if (name.startsWith("set") && name.length() > 3 && paramTypes.length == 1) {
- name = name.substring(3);
- Method getter = getterMap.get(name);
- if (getter != null) {
- try {
- Object value = getter.invoke(source);
- if (value != null) {
- Type paramType = paramTypes[0];
- if (isZteClass(paramType)) {
- try {
- value = copyPropVal(value, ((Class<?>) paramType).newInstance(), copyNull);
- } catch (InstantiationException e) {
- }
- } else if (checkCopyAsList(value, paramType)) {
- Type actualType = ((ParameterizedType) paramType).getActualTypeArguments()[0];
- value = makeTargetList((List<?>) value, (Class<?>) actualType, copyNull);
- } else if (checkCopyAsMap(value, paramType)) {
- Type keyType = ((ParameterizedType) paramType).getActualTypeArguments()[0];
- Type valType = ((ParameterizedType) paramType).getActualTypeArguments()[1];
- try {
- value = makeTargetMap((Map<?, ?>) value, keyType, valType, copyNull);
- } catch (Exception e) {
- value = null;
- }
- }
- setter.invoke(target, value);
- } else if (copyNull) {
- setter.invoke(target, value);
- }
- } catch (IllegalArgumentException e) {
- // do nothing
- } catch (IllegalAccessException e) {
- // do nothing
- } catch (InvocationTargetException e) {
- // do nothing
- }
- }
- }
- }
- return target;
- }
- public static <T> T copyAs(Object srcBean, Class<T> targetClass) {
- if (srcBean == null) {
- return null;
- }
- T ret;
- try {
- ret = targetClass.newInstance();
- } catch (Exception e) {
- e.printStackTrace();
- return null;
- }
- return copyPropVal(srcBean, ret);
- }
- /**
- * 判断Value是否是List类型,type是泛型List,从而他们可以作为List进行bean Copy
- *
- * @param value
- * @param type
- * @return
- */
- private static boolean checkCopyAsList(Object value, Type type) {
- if (!(value instanceof List) || !(type instanceof ParameterizedType))
- return false;
- ParameterizedType paramType = (ParameterizedType) type;
- if (!(paramType.getRawType() instanceof Class))
- return false;
- Class<?> rawType = (Class<?>) paramType.getRawType();
- if (!List.class.isAssignableFrom(rawType) || paramType.getActualTypeArguments().length != 1)
- return false;
- return true;
- }
- /**
- * 判断Value是否是Map类型,type是泛型Map,从而他们可以作为Map进行bean Copy
- *
- * @param value
- * @param type
- * @return
- */
- private static boolean checkCopyAsMap(Object value, Type type) {
- if (!(value instanceof Map) || !(type instanceof ParameterizedType))
- return false;
- ParameterizedType paramType = (ParameterizedType) type;
- if (!(paramType.getRawType() instanceof Class))
- return false;
- Class<?> rawType = (Class<?>) paramType.getRawType();
- if (!Map.class.isAssignableFrom(rawType) || paramType.getActualTypeArguments().length != 2)
- return false;
- return true;
- }
- @SuppressWarnings("unchecked")
- public static <T> List<T> makeTargetList(List<?> sourceList, Class<T> targetClzz, boolean copyNull) {
- if (sourceList == null || targetClzz == null)
- return null;
- List<T> ret = new ArrayList<T>();
- for (Object source : sourceList) {
- if (isZteClass(targetClzz)) {
- try {
- T target = targetClzz.newInstance();
- ret.add(copyPropVal(source, target, copyNull));
- } catch (Exception e) {
- // do nothing
- }
- } else if (targetClzz.isInstance(source)) {
- ret.add((T) source);
- }
- }
- return ret;
- }
- public static <T> List<T> makeTargetList(List<?> sourceList, Class<T> targetClzz) {
- return makeTargetList(sourceList, targetClzz, true);
- }
- public static <T, S> Pagination<T> makePagination(Pagination<S> src, Class<T> targetClzz) {
- if (src == null)
- return null;
- Pagination<T> result = new Pagination<T>(src.getCurIndex(), src.getPageSize(), src.getRowsCount());
- List<T> items = makeTargetList(src.getItems(), targetClzz);
- result.setItems(items);
- return result;
- }
- public static boolean hasText(String textValue) {
- return textValue != null && !"".equals(textValue);
- }
- public static boolean hasDate(Date dateValue) {
- return dateValue != null;
- }
- public static boolean hasNumeric(Integer numeric) {
- return numeric != null;
- }
- /**
- * 获取字符串的长度,如果有中文,则每个中文字符计为2位
- *
- * @param value
- * 指定的字符串
- * @return 字符串的长度
- */
- public static int length(String value) {
- int valueLength = 0;
- String chinese = "[\u0391-\uFFE5]";
- /* 获取字段值的长度,如果含中文字符,则每个中文字符长度为2,否则为1 */
- for (int i = 0; i < value.length(); i++) {
- /* 获取一个字符 */
- String temp = String.valueOf(value.charAt(i));
- /* 判断是否为中文字符 */
- if (temp.matches(chinese)) {
- /* 中文字符长度为2 */
- valueLength += 2;
- } else {
- /* 其他字符长度为1 */
- valueLength += 1;
- }
- }
- return valueLength;
- }
- }
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author Administrator
* @date 2013-4-27 上午10:51:14
* @since 1.0
*/
public class ObjectUtil {
/**
* <p>
* 把原对象的属性值拷贝到目标对象,并返回目标对象.<b>拷贝空值</b>.
* </p>
*
* @param source
* 数据来源对象
* @param target
* 目标对象
* @return 目标对象
*/
public static <T> T copyPropVal(Object source, T target) {
return copyPropVal(source, target, true);
}
/**
* 把原对象的属性值拷贝到目标对象,并返回目标对象;不处理复合属性;<b>不拷贝空值</b>
*
* @param <T>
* @param source
* @param target
* @return 目标对象
*/
public static <T> T copyNotNullPropVal(Object source, T target) {
return copyPropVal(source, target, false);
}
private static Object callGetter(Object o, List<Method> getterList) {
if (getterList == null || o == null)
return null;
for (Method m : getterList) {
if (!m.getReturnType().equals(void.class) && m.getParameterTypes().length == 0) {
try {
return m.invoke(o);
} catch (Exception e) {
}
}
}
return null;
}
private static void callSetter(Object o, Object val, List<Method> setterList) {
if (setterList == null || o == null)
return;
for (Method m : setterList) {
if (m.getReturnType().equals(void.class) && m.getParameterTypes().length == 1) {
try {
m.invoke(o, val);
return;
} catch (Exception e) {
}
}
}
}
/**
* 见prepareToSave,空值默认<b>不</b>覆盖
*
* @param savingEntity
* 要保存到数据库的实体对象
* @param valueEntity
* 数值实体
* @param userId
* 当前用户ID
* @return 处理以后的参数savingEntity
*/
public static <T> T prepareToSave(T savingEntity, Object valueEntity, String userId) {
return prepareToSave(savingEntity, valueEntity, userId, false);
}
/**
* 在保存savingEntity实体之前,完成对savingEntity字段值的设置操作,具体如下:<br>
* 1)设置savingEntity的通用字段getDisabled(isDisabled), getCreateTime,
* getCreatedBy,setCreateTime,setCreateBy,setUpdateTime,setUpdateBy 2)拷贝
* 数值实体valueEntity 所有属性值到savingEntity相应属性<br>
* 本方法返回待保存的实体
*
* @param <T>
* @param savingEntity
* 要保存到数据库的实体对象
* @param valueEntity
* 数值实体
* @param userId
* 当前用户ID
* @param copyNull
* 是否拷贝空值
* @return 处理以后的参数savingEntity
*/
public static <T> T prepareToSave(T savingEntity, Object valueEntity, String userId, boolean copyNull) {
if (savingEntity == null)
return savingEntity;
HashMap<String, List<Method>> methodMap = new HashMap<String, List<Method>>();
for (Method m : savingEntity.getClass().getMethods()) {
List<Method> list = methodMap.get(m.getName());
if (list == null) {
list = new ArrayList<Method>();
methodMap.put(m.getName(), list);
}
list.add(m);
}
Object createTime = callGetter(savingEntity, methodMap.get("getCreateTime"));
Object createBy = callGetter(savingEntity, methodMap.get("getCreateBy"));
copyPropVal(valueEntity, savingEntity, copyNull);
Date now = new Date();
if (createTime == null)
createTime = now;
if (createBy == null)
createBy = userId;
// ~~exam or ERP~~
Object creationDate = callGetter(savingEntity, methodMap.get("getCreationDate"));
Object createdBy = callGetter(savingEntity, methodMap.get("getCreatedBy"));
if (createdBy == null)
createdBy = userId;
if (creationDate == null)
creationDate = now;
// ~~exam or ERP~~
Object disabled = callGetter(savingEntity, methodMap.get("getDisabled"));
if (disabled == null)
disabled = callGetter(savingEntity, methodMap.get("isDisabled"));
if (disabled == null)
callSetter(savingEntity, false, methodMap.get("setDisabled"));
callSetter(savingEntity, createBy, methodMap.get("setCreateBy"));
callSetter(savingEntity, createTime, methodMap.get("setCreateTime"));
callSetter(savingEntity, now, methodMap.get("setUpdateTime"));
callSetter(savingEntity, userId, methodMap.get("setUpdateBy"));
// ~~exam or ERP~~
callSetter(savingEntity, createdBy, methodMap.get("setCreatedBy"));
callSetter(savingEntity, creationDate, methodMap.get("setCreationDate"));
callSetter(savingEntity, now, methodMap.get("setLastUpdateDate"));
callSetter(savingEntity, userId, methodMap.get("setLastUpdatedBy"));
callSetter(savingEntity, userId, methodMap.get("setLastUpdateLogin"));
// ~~exam or ERP~~
return savingEntity;
}
private static boolean isZteClass(Type type) {
if (!(type instanceof Class))
return false;
DataObjectDescriptor annotation = ((Class<?>) type).getAnnotation(DataObjectDescriptor.class);
return annotation != null;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private static Map<?, ?> makeTargetMap(Map<?, ?> source, Type keyType, Type valType, boolean copyNull)
throws Exception {
if (!(keyType instanceof Class))
throw new UnsupportedOperationException("makeTargetMap " + keyType);
Class<?> keyClzz = (Class<?>) keyType;
Map result = new HashMap();
for (Object k : source.keySet()) {
Object srcVal = source.get(k);
Object value = srcVal;
Object key = k;
if (isZteClass(keyClzz))
key = copyNotNullPropVal(k, keyClzz.newInstance());
if (isZteClass(valType)) {
value = copyPropVal(srcVal, ((Class<?>) valType).newInstance(), copyNull);
} else if (checkCopyAsList(srcVal, valType)) {
Type actualType = ((ParameterizedType) valType).getActualTypeArguments()[0];
value = makeTargetList((List<?>) srcVal, (Class<?>) actualType, copyNull);
} else if (checkCopyAsMap(srcVal, valType)) {
ParameterizedType prmType = (ParameterizedType) valType;
Type subKeyType = prmType.getActualTypeArguments()[0];
Type subValType = prmType.getActualTypeArguments()[1];
value = makeTargetMap((Map<?, ?>) srcVal, subKeyType, subValType, copyNull);
}
result.put(key, value);
}
return result;
}
/**
* 把原对象的属性值拷贝到目标对象,并返回目标对象;不处理复合属性,可控制是否拷贝空值
*
* @param <T>
* @param source
* @param target
* @param copyNull
* 是否拷贝空值
* @return 目标对象
*/
public static <T> T copyPropVal(Object source, T target, boolean copyNull) {
if (source == null || target == null)
return target;
Map<String, Method> getterMap = new HashMap<String, Method>();
for (Method m : source.getClass().getMethods()) {
if (m.getParameterTypes().length > 0)
continue;
String name = m.getName();
if (name.startsWith("get") && name.length() > 3) {
name = name.substring(3);
getterMap.put(name, m);
} else if (name.startsWith("is") && name.length() > 2 && m.getReturnType() == boolean.class) {
name = name.substring(2);
getterMap.put(name, m);
}
}
for (Method setter : target.getClass().getMethods()) {
String name = setter.getName();
Type[] paramTypes = setter.getGenericParameterTypes();
if (name.startsWith("set") && name.length() > 3 && paramTypes.length == 1) {
name = name.substring(3);
Method getter = getterMap.get(name);
if (getter != null) {
try {
Object value = getter.invoke(source);
if (value != null) {
Type paramType = paramTypes[0];
if (isZteClass(paramType)) {
try {
value = copyPropVal(value, ((Class<?>) paramType).newInstance(), copyNull);
} catch (InstantiationException e) {
}
} else if (checkCopyAsList(value, paramType)) {
Type actualType = ((ParameterizedType) paramType).getActualTypeArguments()[0];
value = makeTargetList((List<?>) value, (Class<?>) actualType, copyNull);
} else if (checkCopyAsMap(value, paramType)) {
Type keyType = ((ParameterizedType) paramType).getActualTypeArguments()[0];
Type valType = ((ParameterizedType) paramType).getActualTypeArguments()[1];
try {
value = makeTargetMap((Map<?, ?>) value, keyType, valType, copyNull);
} catch (Exception e) {
value = null;
}
}
setter.invoke(target, value);
} else if (copyNull) {
setter.invoke(target, value);
}
} catch (IllegalArgumentException e) {
// do nothing
} catch (IllegalAccessException e) {
// do nothing
} catch (InvocationTargetException e) {
// do nothing
}
}
}
}
return target;
}
public static <T> T copyAs(Object srcBean, Class<T> targetClass) {
if (srcBean == null) {
return null;
}
T ret;
try {
ret = targetClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
return null;
}
return copyPropVal(srcBean, ret);
}
/**
* 判断Value是否是List类型,type是泛型List,从而他们可以作为List进行bean Copy
*
* @param value
* @param type
* @return
*/
private static boolean checkCopyAsList(Object value, Type type) {
if (!(value instanceof List) || !(type instanceof ParameterizedType))
return false;
ParameterizedType paramType = (ParameterizedType) type;
if (!(paramType.getRawType() instanceof Class))
return false;
Class<?> rawType = (Class<?>) paramType.getRawType();
if (!List.class.isAssignableFrom(rawType) || paramType.getActualTypeArguments().length != 1)
return false;
return true;
}
/**
* 判断Value是否是Map类型,type是泛型Map,从而他们可以作为Map进行bean Copy
*
* @param value
* @param type
* @return
*/
private static boolean checkCopyAsMap(Object value, Type type) {
if (!(value instanceof Map) || !(type instanceof ParameterizedType))
return false;
ParameterizedType paramType = (ParameterizedType) type;
if (!(paramType.getRawType() instanceof Class))
return false;
Class<?> rawType = (Class<?>) paramType.getRawType();
if (!Map.class.isAssignableFrom(rawType) || paramType.getActualTypeArguments().length != 2)
return false;
return true;
}
@SuppressWarnings("unchecked")
public static <T> List<T> makeTargetList(List<?> sourceList, Class<T> targetClzz, boolean copyNull) {
if (sourceList == null || targetClzz == null)
return null;
List<T> ret = new ArrayList<T>();
for (Object source : sourceList) {
if (isZteClass(targetClzz)) {
try {
T target = targetClzz.newInstance();
ret.add(copyPropVal(source, target, copyNull));
} catch (Exception e) {
// do nothing
}
} else if (targetClzz.isInstance(source)) {
ret.add((T) source);
}
}
return ret;
}
public static <T> List<T> makeTargetList(List<?> sourceList, Class<T> targetClzz) {
return makeTargetList(sourceList, targetClzz, true);
}
public static <T, S> Pagination<T> makePagination(Pagination<S> src, Class<T> targetClzz) {
if (src == null)
return null;
Pagination<T> result = new Pagination<T>(src.getCurIndex(), src.getPageSize(), src.getRowsCount());
List<T> items = makeTargetList(src.getItems(), targetClzz);
result.setItems(items);
return result;
}
public static boolean hasText(String textValue) {
return textValue != null && !"".equals(textValue);
}
public static boolean hasDate(Date dateValue) {
return dateValue != null;
}
public static boolean hasNumeric(Integer numeric) {
return numeric != null;
}
/**
* 获取字符串的长度,如果有中文,则每个中文字符计为2位
*
* @param value
* 指定的字符串
* @return 字符串的长度
*/
public static int length(String value) {
int valueLength = 0;
String chinese = "[\u0391-\uFFE5]";
/* 获取字段值的长度,如果含中文字符,则每个中文字符长度为2,否则为1 */
for (int i = 0; i < value.length(); i++) {
/* 获取一个字符 */
String temp = String.valueOf(value.charAt(i));
/* 判断是否为中文字符 */
if (temp.matches(chinese)) {
/* 中文字符长度为2 */
valueLength += 2;
} else {
/* 其他字符长度为1 */
valueLength += 1;
}
}
return valueLength;
}
}
DataObjectDescriptor.java
- import java.lang.annotation.Documented;
- import java.lang.annotation.Retention;
- import java.lang.annotation.RetentionPolicy;
- import java.lang.annotation.Target;
- @Retention(RetentionPolicy.RUNTIME)
- @Target({ java.lang.annotation.ElementType.TYPE })
- @Documented
- public @interface DataObjectDescriptor {
- public abstract String value();
- }
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ java.lang.annotation.ElementType.TYPE })
@Documented
public @interface DataObjectDescriptor {
public abstract String value();
}
DaoException.java
- import org.springframework.core.NestedRuntimeException;
- /**
- * @author
- */
- public class DaoException extends NestedRuntimeException {
- private static final long serialVersionUID = 1L;
- public DaoException(String msg) {
- super(msg);
- }
- public DaoException(String msg, Throwable obj) {
- super(msg, obj);
- }
- }
import org.springframework.core.NestedRuntimeException;
/**
* @author
*/
public class DaoException extends NestedRuntimeException {
private static final long serialVersionUID = 1L;
public DaoException(String msg) {
super(msg);
}
public DaoException(String msg, Throwable obj) {
super(msg, obj);
}
}
SessionTimeoutException.java
- import org.springframework.core.NestedRuntimeException;
- public class SessionTimeoutException extends NestedRuntimeException {
- private static final long serialVersionUID = 1L;
- public SessionTimeoutException(String msg) {
- super(msg);
- }
- public SessionTimeoutException(String msg, Throwable obj) {
- super(msg, obj);
- }
- }
import org.springframework.core.NestedRuntimeException;
public class SessionTimeoutException extends NestedRuntimeException {
private static final long serialVersionUID = 1L;
public SessionTimeoutException(String msg) {
super(msg);
}
public SessionTimeoutException(String msg, Throwable obj) {
super(msg, obj);
}
}
PagerFactory.java
- import java.util.ArrayList;
- import java.util.List;
- public class PagerFactory {
- public static <T> Pagination<T> createEmpty() {
- return create(1, 10);
- }
- public static <T> Pagination<T> create(Number pageIndex, Number pageSize) {
- return create(pageIndex, pageSize, 0, new ArrayList<T>(0));
- }
- public static <T> Pagination<T> create(Number pageIndex, Number pageSize, Number rowsCount) {
- return create(pageIndex, pageSize, rowsCount, new ArrayList<T>(0));
- }
- public static <T> Pagination<T> create(Number pageIndex, Number pageSize, Number rowsCount, List<T> data) {
- Pagination<T> p = new Pagination<T>(pageIndex.longValue(), pageSize.longValue(), rowsCount.longValue());
- if (data == null) {
- data = new ArrayList<T>(0);
- }
- p.setItems(data);
- return p;
- }
- public static <T> List<T> getPaginList(List<T> allList, int pageIndex, int pageSize) {
- List<T> result = new ArrayList<T>();
- int start = pageIndex < 2 ? 0 : ((pageIndex - 1) * pageSize);
- int end = start + pageSize > allList.size() ? allList.size() : start + pageSize;
- for (int i = start; i < end; i++) {
- result.add(allList.get(i));
- }
- return result;
- }
- }
import java.util.ArrayList;
import java.util.List;
public class PagerFactory {
public static <T> Pagination<T> createEmpty() {
return create(1, 10);
}
public static <T> Pagination<T> create(Number pageIndex, Number pageSize) {
return create(pageIndex, pageSize, 0, new ArrayList<T>(0));
}
public static <T> Pagination<T> create(Number pageIndex, Number pageSize, Number rowsCount) {
return create(pageIndex, pageSize, rowsCount, new ArrayList<T>(0));
}
public static <T> Pagination<T> create(Number pageIndex, Number pageSize, Number rowsCount, List<T> data) {
Pagination<T> p = new Pagination<T>(pageIndex.longValue(), pageSize.longValue(), rowsCount.longValue());
if (data == null) {
data = new ArrayList<T>(0);
}
p.setItems(data);
return p;
}
public static <T> List<T> getPaginList(List<T> allList, int pageIndex, int pageSize) {
List<T> result = new ArrayList<T>();
int start = pageIndex < 2 ? 0 : ((pageIndex - 1) * pageSize);
int end = start + pageSize > allList.size() ? allList.size() : start + pageSize;
for (int i = start; i < end; i++) {
result.add(allList.get(i));
}
return result;
}
}