hibenate 기반 BaseDAO 인터페이스
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 {
/**
*
*
* @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 get(Class entityClass, Serializable id);
/**
* , 。
*
* @param queryString
*
* @param params
*
* @return , ,
*/
@SuppressWarnings("hiding")
T get(CharSequence queryString, Map params);
/**
* , 。
*
* @param queryString
*
* @param params
*
* @return , ,
*/
@SuppressWarnings("hiding")
T get(CharSequence queryString, Object... params);
/**
*
*
*
* @param queryString
*
* @param params
*
* @return
*/
@SuppressWarnings("hiding")
List findList(CharSequence queryString, Object... params);
/**
*
*
*
* @param queryString
*
* @param params
*
* @return
*/
@SuppressWarnings("hiding")
List findList(CharSequence queryString, Map params);
/**
*
*
* @param queryString
*
* @param pageIndex
* , pageIndex<1 , pageSize 。
* @param pageSize
* , pageSize<1 。
* @param params
*
* @return
*/
@SuppressWarnings("hiding")
Pagination 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")
Pagination findPagination(CharSequence queryString, Map params, int pageIndex, int pageSize);
/**
* , , hql
*
* @param queryString
*
* @param countString
*
* @param pageIndex
* , pageIndex<1 , pageSize 。
* @param pageSize
* , pageSize<1 。
* @param params
*
* @return
*/
@SuppressWarnings("hiding")
Pagination 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")
Pagination findPagination(CharSequence queryString, CharSequence countString, Map 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 Pagination findSqlPagination(final CharSequence queryString, final CharSequence countString,
final Map 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 list);
public void insert(List list);
public void delete(List list);
public void update(List list);
public List findByProperty(String name, Object value);
public List findByProperty(Map conditionMap);
/**
*
*
*
* @param queryString
*
* @param maxResults
*
* @param params
*
* @return
*/
public List findListByMax(CharSequence queryString, int maxResults, Object... params);
/**
*
*
*
* @param queryString
*
* @param maxResults
*
* @param params
*
* @return
*/
public List findListByMax(CharSequence queryString, int maxResults, Map 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 implements BaseDao {
protected Class entityClazz;
protected SessionFactory sessionFactory;
@SuppressWarnings("unchecked")
public BaseDaoImpl() {
Type type = getClass().getGenericSuperclass();
if (type instanceof ParameterizedType) {
this.entityClazz = (Class) ((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 get(Class entityClass, Serializable id) {
return (T) getSession().get(entityClass, id);
}
@SuppressWarnings({ "unchecked", "rawtypes", "hiding" })
public 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 get(CharSequence queryString, Map 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 List 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 List findList(CharSequence queryString, Map params) {
Query query = getSession().createQuery(queryString.toString());
setParameter(query, params);
return query.list();
}
@SuppressWarnings({ "unchecked", "hiding" })
public Pagination 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 Pagination findPagination(CharSequence queryString, Map 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 Pagination 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 Pagination findPagination(CharSequence queryString, CharSequence countString,
Map 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 Pagination findSqlPagination(CharSequence queryString, final CharSequence countString,
final Map 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 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 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 list) {
saveOrUpdateAll(list);
}
@Override
public T insert(T entity) {
save(entity);
return entity;
}
@Override
public void insert(List entitys) {
for (T entity : entitys) {
save(entity);
}
}
@Override
public void update(List entitys) {
for (T entity : entitys) {
update(entity);
}
}
@Override
public List findByProperty(String name, Object value) {
String hql = "from " + entityClazz.getSimpleName() + " where " + name + "=? ";
return findList(hql, value);
}
@Override
public List findByProperty(Map conditionMap) {
StringBuilder hql = new StringBuilder();
hql.append("from " + entityClazz.getSimpleName());
if (!conditionMap.isEmpty()) {
Iterator 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 List findListByMax(final CharSequence queryString, final int maxResults, final Object... params) {
@SuppressWarnings({ "unchecked", "serial" })
List list = (List) executeQuery(new HibernateHandler() {
@Override
public List 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 List findListByMax(final CharSequence queryString, final int maxResults,
final Map params) {
@SuppressWarnings({ "unchecked", "serial" })
List list = (List) executeQuery(new HibernateHandler() {
@Override
public List doInHibernate(Session paramSession) {
try {
Query query = paramSession.createQuery(queryString.toString());
for (Iterator 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 cal = new ThreadLocal() {
@Override
protected Calendar initialValue() {
return Calendar.getInstance();
}
};
/** HQL/SQL */
public final List
HibernateHandler.java
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 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 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 getItems() {
return items;
}
/**
*
*
* @param items
*/
public void setItems(List 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 {
/**
*
* , . .
*
*
* @param source
*
* @param target
*
* @return
*/
public static T copyPropVal(Object source, T target) {
return copyPropVal(source, target, true);
}
/**
* , ; ;
*
* @param
* @param source
* @param target
* @return
*/
public static T copyNotNullPropVal(Object source, T target) {
return copyPropVal(source, target, false);
}
private static Object callGetter(Object o, List 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 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,
*
* @param savingEntity
*
* @param valueEntity
*
* @param userId
* ID
* @return savingEntity
*/
public static T prepareToSave(T savingEntity, Object valueEntity, String userId) {
return prepareToSave(savingEntity, valueEntity, userId, false);
}
/**
* savingEntity , savingEntity , :
* 1) savingEntity getDisabled(isDisabled), getCreateTime,
* getCreatedBy,setCreateTime,setCreateBy,setUpdateTime,setUpdateBy 2)
* valueEntity savingEntity
*
*
* @param
* @param savingEntity
*
* @param valueEntity
*
* @param userId
* ID
* @param copyNull
*
* @return savingEntity
*/
public static T prepareToSave(T savingEntity, Object valueEntity, String userId, boolean copyNull) {
if (savingEntity == null)
return savingEntity;
HashMap> methodMap = new HashMap>();
for (Method m : savingEntity.getClass().getMethods()) {
List list = methodMap.get(m.getName());
if (list == null) {
list = new ArrayList();
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
* @param source
* @param target
* @param copyNull
*
* @return
*/
public static T copyPropVal(Object source, T target, boolean copyNull) {
if (source == null || target == null)
return target;
Map getterMap = new HashMap();
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 copyAs(Object srcBean, Class 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 List makeTargetList(List> sourceList, Class targetClzz, boolean copyNull) {
if (sourceList == null || targetClzz == null)
return null;
List ret = new ArrayList();
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 List makeTargetList(List> sourceList, Class targetClzz) {
return makeTargetList(sourceList, targetClzz, true);
}
public static Pagination makePagination(Pagination src, Class targetClzz) {
if (src == null)
return null;
Pagination result = new Pagination(src.getCurIndex(), src.getPageSize(), src.getRowsCount());
List 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();
}
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);
}
}
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);
}
}
PagerFactory.java
import java.util.ArrayList;
import java.util.List;
public class PagerFactory {
public static Pagination createEmpty() {
return create(1, 10);
}
public static Pagination create(Number pageIndex, Number pageSize) {
return create(pageIndex, pageSize, 0, new ArrayList(0));
}
public static Pagination create(Number pageIndex, Number pageSize, Number rowsCount) {
return create(pageIndex, pageSize, rowsCount, new ArrayList(0));
}
public static Pagination create(Number pageIndex, Number pageSize, Number rowsCount, List data) {
Pagination p = new Pagination(pageIndex.longValue(), pageSize.longValue(), rowsCount.longValue());
if (data == null) {
data = new ArrayList(0);
}
p.setItems(data);
return p;
}
public static List getPaginList(List allList, int pageIndex, int pageSize) {
List result = new ArrayList();
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;
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.