freemaker的配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="freeMarkerConfigurer" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="freemarkerSettings">
<props>
<prop key="default_encoding">UTF-8</prop>
<prop key="date_format">yyyy-MM-dd</prop>
<prop key="time_format">HH:mm</prop>
<prop key="datetime_format">yyyy-MM-dd HH:mm</prop>
<prop key="number_format">#.########</prop>
<!-- 出现异常时的处理方式,debug为在后台输出异常并抛出异常,html_debug为在后台和页面输出异常,rethrow为不做处理直接抛出异常,ignore为在后台输出异常但在页面忽略异常 -->
<prop key="template_exception_handler">ignore</prop>
<!-- 是否不处理空值 -->
<prop key="classic_compatible">true</prop>
<prop key="auto_import">static/comm/commons.ftl as page</prop>
</props>
</property>
<property name="templateLoaderPath" value="/" />
</bean>
<bean id="freeMarkerViewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<!-- 模板是否可以直接获取request的值 -->
<property name="exposeRequestAttributes" value="true" />
<!-- 模板是否可以直接获取session的值 -->
<property name="exposeSessionAttributes" value="false" />
<property name="prefix" value="/" />
<property name="suffix" value=".ftl" />
<property name="contentType" value="text/html; charset=UTF-8" />
</bean>
<!-- 获取WebApplicationContext -->
<bean class="com.util.WebApplicationContextUtil" /> 获取工具类
</beans>
spring核心文件 扫描控制层
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
<context:component-scan base-package="com.guu.uurms.controller">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--文件上传 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="200000000" />
</bean>
</beans>
扫描任务调度
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd">
<context:component-scan base-package="com.task"/>
<task:executor id="executor" pool-size="15"/> 任务调度并发数
<task:scheduler id="scheduler" pool-size="30"/> 任务调度的最大任务数量
<task:annotation-driven executor="executor" scheduler="scheduler"/>
</beans>
dwr的扫描
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:dwr="http://www.directwebremoting.org/schema/spring-dwr"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.directwebremoting.org/schema/spring-dwr http://www.directwebremoting.org/schema/spring-dwr-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<dwr:configuration/>
<dwr:annotation-scan base-package="com.dwr" scanDataTransferObject="false"/>
</beans>
注解的方式获取实体
<context:annotation-config /> 注解方式使用实体bean
<context:component-scan base-package="com..dao.jdbcimpl" />
<!-- 用annotation的bean不需要配置hbm.xml -->
<property name="packagesToScan">
<bean>的bean的形式配置数据源》
<list>
<value>com.**.po</value>
</list>
</property>
<配置sessionFactory>
<!-- 配置事物 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
三个规范文件
/
* DAOBean的命名规则是将DAO的首子母大写并将DAO_IMPLEMENT_SUFFIX后缀去掉
*/
public class DAOBeanNameGenerator implements BeanNameGenerator {
private final Log LOG = LogFactory.getLog(getClass());
private static final String DAO_IMPLEMENT_SUFFIX = "Implement";
public String generateBeanName(BeanDefinition definition,BeanDefinitionRegistry registry) {
String beanName = StringUtils.capitalize(StringUtils.unqualify(definition.getBeanClassName()));
beanName = beanName.endsWith(DAO_IMPLEMENT_SUFFIX)?beanName.substring(0,beanName.length()-DAO_IMPLEMENT_SUFFIX.length()):beanName;
LOG.info("generateBeanName:"+beanName);
return beanName;
}
/**
* Sequence的命名规则是将bean的大写字母用_分开,小写字母转大写,最后加上_S的后�?
*/
public class BaseBeanSequenceGenerator extends SequenceGenerator {
@Override
public void configure(Type type,Properties params,Dialect dialect) throws MappingException {
//System.out.println("configure("+type+","+params+","+dialect);
if(!params.containsKey(SequenceGenerator.SEQUENCE)) {
String tableName = params.getProperty("identity_tables");
if(tableName==null) tableName = params.getProperty("target_table");
if(tableName==null) throw new MappingException("unknows table name:"+params);
params.setProperty(SequenceGenerator.SEQUENCE,tableName+"_S");
}
super.configure(type,params,dialect);
}
public class BaseBeanNamingStrategy extends EJB3NamingStrategy {
private static final long serialVersionUID = -5742401920577663212L;
public static final NamingStrategy INSTANCE = new BaseBeanNamingStrategy();
@Override
public String propertyToColumnName(String propertyName) {
return addUnderscores(propertyName);
}
@Override
public String classToTableName(String className) {
return addUnderscores(className.replace("Bean",""));
}
private static String addUnderscores(String name) {
StringBuilder sb = new StringBuilder(name.replace('.','_'));
int i = 0;
while(i < sb.length()) {
if(Character.isLowerCase(sb.charAt(i++))) {
if(i>2) sb.insert(i-2,'_');
break;
}
}
while(i<sb.length()-1) {
if(Character.isLowerCase(sb.charAt(i-1)) && Character.isUpperCase(sb.charAt(i)) && Character.isLowerCase(sb.charAt(i+1))) {
sb.insert(i++,'_');
}
i++;
}
return sb.toString().toUpperCase();
}
/**
* Entity的表名和字段名命名规则是将大写字母用_分开,小写字母转大写,结尾的Bean去掉
*/
public class BaseBeanNamingStrategy extends EJB3NamingStrategy {
private static final long serialVersionUID = -5742401920577663212L;
public static final NamingStrategy INSTANCE = new BaseBeanNamingStrategy();
@Override
public String propertyToColumnName(String propertyName) {
return addUnderscores(propertyName);
}
@Override
public String classToTableName(String className) {
return addUnderscores(className.replace("Bean",'_');
}
i++;
}
return sb.toString().toUpperCase();
}
package com.guu.uurms.dao.base;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;
/**
* DAO的base类 定义通用的抽象方法
*/
public interface BaseDAO<T extends Serializable> {
/**
* 根据sid得到对像
*
* @param sid
* @return
*/
public abstract T getBeanBySid(Long sid);
/**
* 保存对像
*
* @param bean
* @return
*/
public abstract void saveBean(T obj);
/**
* 更新对像
*
* @param obj
* @return
*/
public abstract void updateBean(T obj);
/**
* 删除对像
*
* @param obj
* @return
*/
public abstract void deleteBean(T obj);
/**
* 根据条件查找记录并分页
*
* @param eqName
* @param eqValue
* @param currypage
* @param pagesize
* @return
*/
public abstract List<T> getBeanListByEq(String eqName,Object eqValue,int currypage,int pagesize);
/**
* 根据条件查找记录并分页排序
*
* @param eqName
* @param eqValue
* @param currypage
* @param pagesize
* @param order
* @param asc
* @return
*/
public abstract List<T> getBeanListByEq(String eqName,int pagesize,String order,boolean asc);
/**
* 根据条件获取记录总数
*
* @param eqName
* @param eqValue
* @return
*/
public abstract long getBeanCountByEq(String eqName,Object eqValue);
/**
* 根据条件查找记录并分页
*
* @param eq
* @param currypage
* @param pagesize
* @return
*/
public abstract List<T> getBeanListByEq(Map<String,Object> eq,int pagesize);
/**
* 根据条件查找记录并分页排序
*
* @param eq
* @param currypage
* @param pagesize
* @param order
* @param asc
* @return
*/
public abstract List<T> getBeanListByEq(Map<String,boolean asc);
/**
* 根据条件获取记录总数
*
* @param eq
* @return
*/
public abstract long getBeanCountByEq(Map<String,Object> eq);
/**
* 查找记录并分页
*
* @param currypage
* @param pagesize
* @return
*/
public abstract List<T> getBeanList(int currypage,int pagesize);
/**
* 查找记录并分页排序
*
* @param currypage
* @param pagesize
* @param order
* @param asc
* @return
*/
public abstract List<T> getBeanList(int currypage,boolean asc);
/**
* 获取记录总数
*
* @return
*/
public abstract long getBeanCount();
/**
* 查找所有记录
*
* @return
*/
public abstract List<T> getBeanList();
/**
* 查找所有记录并排序
*
* @param order
* @param asc
* @return
*/
public abstract List<T> getBeanList(String order,boolean asc);
/**
* 根据条件查找记录
*
* @param eqName
* @param eqValue
* @return
*/
public abstract List<T> getBeanListByEq(String eqName,Object eqValue);
/**
* 根据条件查找记录并排序
*
* @param eqName
* @param eqValue
* @param order
* @param asc
* @return
*/
public abstract List<T> getBeanListByEq(String eqName,boolean asc);
/**
* 根据条件查找记录
*
* @param eq
* @return
*/
public abstract List<T> getBeanListByEq(Map<String,Object> eq);
/**
* 根据条件查找记录并排序
*
* @param eq
* @param order
* @param asc
* @return
*/
public abstract List<T> getBeanListByEq(Map<String,boolean asc);
/**
* 根据条件得到唯一对像
*
* @param eqName
* @param eqValue
* @return
*/
public abstract T getBeanByEq(String eqName,Object eqValue);
/**
* 根据条件得到唯一对像
*
* @param eq
* @return
*/
public abstract T getBeanByEq(Map<String,Object> eq);
/**
* 根据sid删除记录
* @param sid
*/
public abstract void deleteBeanBySid(Long sid);
/**
* 根据sid列表删除记录
* @param sid
* @return 成功删除的记录数
*/
public abstract int deleteBeanBySid(List<Long> sid);
/**
* 根据sid数组删除记录
* @param sid
* @return 成功删除的记录数
*/
public abstract int deleteBeanBySid(String[] sid);
/**
* 根据条件删除记录
*
* @param eqName
* @param eqValue
* @return
*/
public abstract int deleteBeanByEq(String eqName,Object eqValue);
/**
* 根据条件删除记录
* @param properties key是字段名,value是字段值,如果value是List则以in的方式判断,否则以eq的方式判断
* @return 成功删除的记录数
*/
public abstract int deleteBeanByProperties(Map<String,Object> properties);
/**
* 根据条件查找记录的总数
* @param param
* @param value
* @return
*/
public abstract int getBeanCountByIn(String param,Collection value);
/**
* 根据条件查找记录
* @param param
* @param value
* @return
*/
public abstract List<T> getBeanListByIn(String param,Collection value);
/**
* 根据条件查找记录并分页
* @param param
* @param value
* @param cpage
* @param pagesize
* @return
*/
public abstract List<T> getBeanListByIn(String param,Collection value,int cpage,int pagesize);
/**
* 根据条件查找记录并按照条件排序
* @param param
* @param value
* @param cpage
* @param pagesize
* @param Order
* @param asc
* @return
*/
public abstract List<T> getBeanListByIn(String param,String Order,boolean asc);
/**
* 查找记录并分页排序
* @param currypage
* 小于1则不分页
* @param pagesize
* @param order
* 为null或length为0则不排序
* @param asc
* @return
*/
public abstract List<T> getBeanList(int currypage,String[] order,boolean[] asc);
/**
* 查找记录并排序
* @param order
* 为null或length为0则不排序
* @param asc
* @return
*/
public abstract List<T> getBeanList(String[] order,boolean[] asc);
/**
* 根据条件查找记录并排序
* @param eqName
* 为null或""则不判断
* @param eqValue
* @param currypage
* 小于1则不分页
* @param pagesize
* @param order
* 为null或length为0则不排序
* @param asc
* @return
*/
public abstract List<T> getBeanListByEq(String eqName,boolean[] asc);
/**
* 根据条件查找记录并排序
*
* @param eq
* @param order
* 为null或length为0则不排序
* @param asc
* @return
*/
public abstract List<T> getBeanListByEq(Map<String,boolean[] asc);
/**
* 根据条件查找记录并排序
*
* @param eq
* @param currypage
* 小于1则不分页
* @param pagesize
* @param order
* 为null或length为0则不排序
* @param asc
* @return
*/
public abstract List<T> getBeanListByEq(Map<String,boolean[] asc);
/**
* 根据sid查找记录
* @param sid
* @return
*/
public abstract List<T> getBeanListBySid(List<Long> sid);
/**
* 根据条件不区分大小写模糊查询记录并排序
* @param ilinkName
* @param ilinkValue
* @param currypage
* @param pagesize
* @param order
* @param asc
* @return
*/
public abstract List<T> getBeanListByIlink(String ilinkName,String ilinkValue,boolean asc);
public List<T> getListByIlink(Map<String,Object> ilink,String ordername,boolean asc);
public List<T> getListByEqAndIlink(Map<String,Map<String,boolean asc);
/**
* 根据条件不区分大小写模糊查询记录数
* @param ilinkName
* @param ilinkValue
* @return
*/
public abstract long getBeanCountByIlink(String ilinkName,String ilinkValue);
public abstract long getCountByEqAndIlink(Map<String,Object> ilink);
/**
* 查找所有记录并按照指定的key和value字段返回结果
* @param mapKey 保存在key的字段
* @param mapValue 保存在value的字段
* @return
*/
public abstract Map getBeanMap(String mapKey,String mapValue);
/**
* 根据条件查询记录并按照指定的key和value字段返回结果
* @param mapKey 保存在key的字段
* @param mapValue 保存在value的字段
* @return
*/
public abstract Map getBeanMap(String mapKey,String mapValue,boolean asc);
/**
* 根据条件得到唯一对像,并且将其它重复的记录删除
* @param eqName
* @param eqValue
* @return
*/
public abstract T getBeanBySidAndDeleteRepeat(String eqName,Object eqValue);
public abstract long getBeanCountByMultiCondition(Object[][] conditionList);
public abstract List<T> getBeanListByMultiCondition(Object[][] conditionList,Object[][] orderlist);
}
package com.guu.uurms.dao.base;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.sqlException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Pattern;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projection;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Property;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.guu.uurms.po.base.BaseBean;
/**
* DAO的base实现类 实现BaseDAO的抽象方法及通用方法
*
* @author 华理德
* @date 2009-04-09
*/
@SuppressWarnings("unchecked")
public abstract class BaseDAOImplement<T extends Serializable> extends HibernateDaoSupport implements BaseDAO<T> {
private static final Log LOG = LogFactory.getLog(BaseDAOImplement.class);
private Pattern ilikePattern = Pattern.compile("[_%]");
protected Class<T> bean;
@PostConstruct
protected void setBean() throws ClassNotFoundException {
String className = getClass().getSimpleName();
try {
System.out.println(BaseBean.class.getPackage().getName().replace(".base","")+"."+className.replace("DAOImplement","Bean"));
bean = (Class<T>)Class.forName(BaseBean.class.getPackage().getName().replace(".base","Bean"));
} catch(ClassNotFoundException e) {
throw new ClassNotFoundException("BaseDAOImplement无法加载"+getClass().getName()+"的Bean["+e.getMessage()+"]");
}
}
protected Class<T> getBean() {
return bean;
}
@Resource
public void injectSessionFactory(SessionFactory sessionFactory) {
setSessionFactory(sessionFactory);
}
/*
* =======================================================================
* 实现DAOBase的抽象方法
* =======================================================================
*/
public String getIdName() {
return "sid";
}
public void deleteBean(T bean) {
deleteObject(bean);
}
public T getBeanByEq(Map<String,Object> eq) {
return getObjectByEq(eq);
}
public T getBeanByEq(String eqName,Object eqValue) {
return getObjectByEq(eqName,eqValue);
}
public T getBeanBySid(Long sid) {
return getBeanByEq(getIdName(),sid);
}
public List<T> getBeanList(int currypage,int pagesize) {
return getListByEq(null,currypage,pagesize,getIdName(),false);
}
public List<T> getBeanList(int currypage,boolean asc) {
return getListByEq(null,order,asc);
}
public List<T> getBeanList() {
return getListByEq(null,false);
}
public List<T> getBeanList(String order,asc);
}
public List<T> getBeanListByEq(Map<String,int pagesize) {
return getListByEq(eq,false);
}
public List<T> getBeanListByEq(Map<String,boolean asc) {
return getListByEq(eq,Object> eq) {
return getListByEq(eq,asc);
}
public List<T> getBeanListByEq(String eqName,int pagesize) {
return getListByEq(getMap(eqName,eqValue),false);
}
public List<T> getBeanListByEq(String eqName,boolean asc) {
return getListByEq(getMap(eqName,Object eqValue) {
return getListByEq(getMap(eqName,asc);
}
public long getBeanCount() {
return getCountByEq(null);
}
public long getBeanCountByEq(Map<String,Object> allEq) {
return getCountByEq(allEq);
}
public long getBeanCountByEq(String eqName,Object eqValue) {
return getCountByEq(getMap(eqName,eqValue));
}
public void saveBean(T bean) {
saveObject(bean);
}
public void updateBean(T bean) {
updateObject(bean);
}
public void deleteBeanBySid(Long sid) {
deleteObject(getIdName(),sid);
}
public int deleteBeanBySid(List<Long> sid) {
return deleteObject(getIdName(),sid);
}
public int deleteBeanBySid(String[] sid) {
if(sid==null || sid.length==0) return 0;
List<Long> value = new ArrayList<Long>();
for(String id : sid) {
value.add(Long.valueOf(id));
}
return deleteObject(getIdName(),value);
}
public List<T> getBeanList(int currypage,boolean[] asc) {
return getListByEq(null,asc);
}
public List<T> getBeanList(String[] order,
String[] order,boolean[] asc) {
return getListByEq(eqName,eqValue,asc);
}
public List<T> getBeanListByEq(Map<String,boolean[] asc) {
return getListByEq(eq,asc);
}
public int deleteBeanByEq(String eqName,Object eqValue) {
return deleteObject(eqName,eqValue);
}
public int deleteBeanByProperties(final Map<String,Object> properties) {
if(properties == null || properties.isEmpty()) {
return 0;
} else {
return (Integer)getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException,sqlException {
StringBuilder hql = new StringBuilder();
hql.append("delete ");
hql.append(getBean().getName());
hql.append(" where ");
for(Iterator<String> iter = properties.keySet().iterator(); iter.hasNext();) {
String key = iter.next();
Object value = properties.get(key);
hql.append(key);
if(value==null) {
hql.append(" is null");
} else if(value instanceof Collection) {
hql.append(" in (:");
hql.append(key);
hql.append(")");
} else {
hql.append("=:");
hql.append(key);
}
if(iter.hasNext()) hql.append(" and ");
}
Query query = session.createQuery(hql.toString());
query.setProperties(properties);
return query.executeUpdate();
}
});
}
}
public List<T> getBeanListBySid(List<Long> sid) {
return getListByIn(getIdName(),sid,null,false);
}
public List<T> getBeanListByIlink(String ilinkName,boolean asc) {
return getListByIlink(ilinkName,ilinkValue,asc);
}
public long getBeanCountByIlink(String ilinkName,String ilinkValue) {
return getCountByIlink(ilinkName,ilinkValue);
}
public Map getBeanMap(final String mapKey,final String mapValue) {
List<Object[]> result = getHibernateTemplate().find("select "+mapKey+","+mapValue+" from "+getBean().getSimpleName());
Map map = new HashMap();
for(Object[] o:result) {
map.put(o[0],o[1]);
}
return map;
}
public Map getBeanMap(final String mapKey,final String mapValue,final Map<String,final int currypage,final int pagesize,final String order,final boolean asc) {
List<Object[]> result = getHibernateTemplate().executeFind(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException,sqlException {
Criteria c = session.createCriteria(getBean());
if(eq != null && !eq.isEmpty()) {
c.add(Restrictions.allEq(eq));
}
if(currypage > 0) {
c.setFirstResult((currypage - 1) * pagesize);
c.setMaxResults(pagesize);
}
if(order != null) {
c.addOrder(asc?Order.asc(order):Order.desc(order));
}
c.setProjection(Projections.projectionList().add(Property.forName(mapKey)).add(Property.forName(mapValue)));
return c.list();
}});
Map map = new HashMap();
for(Object[] o:result) {
map.put(o[0],o[1]);
}
return map;
}
public T getBeanBySidAndDeleteRepeat(String eqName,Object eqValue) {
List<T> list = getListByEq(eqName,1,1000,true);
if(list.isEmpty()) return null;
if(list.size()>1) {
for(int i = 1; i<list.size(); i++) {
deleteBean(list.get(i));
}
}
return list.get(0);
}
/*
* =======================================================================
* 提供给所有继承该类的子类调用的方法
* =======================================================================
*/
/**
* 根据多种混合的条件(如大于,等于,小于,不等于,包含)分页获取LIST
*
* @param conditionList
* @param currypage
* @param pagesize
* @param orderName
* @param asc
* @return
* @author 杨浚
*/
protected List<T> getListByMultiCondition(final Object[][] conditionList,final String orderName,final boolean asc) {
return getHibernateTemplate().executeFind(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException,sqlException {
Criteria cr = session.createCriteria(getBean());
for(Object[] condition : conditionList) {
addCriteriaCondition(cr,condition);
}
Order order = null;
if(asc) {
order = Order.asc(orderName);
} else {
order = Order.desc(orderName);
}
//order=asc?Order.asc(orderName):Order.desc(orderName);
cr.addOrder(order);
if(currypage!=0 && pagesize !=0){
cr.setMaxResults(pagesize);
cr.setFirstResult((currypage - 1) * pagesize);
}
return cr.list();
}
});
}
/**
* 根据多种混合的条件(如大于,等于,小于,不等于,包含)分页获取LIST 当pagesize<=0时,不进行分页
*
* @param conditionList
* @param currypage
* @param pagesize
* @param orderName
* @param asc
* @return
* @author 杨浚
*/
public List<T> getBeanListByMultiCondition(final Object[][] conditionList,final Object[][] orderlist) {
return getHibernateTemplate().executeFind(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException,condition);
}
addCriteriaOrder(cr,orderlist);
if(currypage!=0 && pagesize !=0) {
cr.setMaxResults(pagesize);
cr.setFirstResult((currypage - 1) * pagesize);
}
return cr.list();
}
});
}
/**
* 把查询条件加入Criteria中。
*
* @param cr
* @param condition
* @author 杨浚
*/
private void addCriteriaCondition(Criteria cr,Object[] condition) {
try {
if(condition!=null&&condition[0] != null && !condition[0].equals("")) {
Method[] methods = Restrictions.class.getMethods();
for(Method mth : methods) {
boolean isThisMethod = false;
if(mth.getName().equals((String)condition[0])) {
isThisMethod = true;
Class[] parameters = mth.getParameterTypes();
try {
if(parameters.length+1!=condition.length){
isThisMethod=false;
}else{
for(int i = 0; i < parameters.length; i++) {
if(!parameters[i].isInstance(condition[i+1])) {
isThisMethod = false;
}
}
}
} catch(Exception e) {
isThisMethod = false;
LOG.error("exception,but nvm!",e);
}
}
if(isThisMethod) {
Object[] desArray = new Object[condition.length - 1];
System.arraycopy(condition,desArray,condition.length - 1);
Criterion re = (Criterion)mth.invoke(null,desArray);
cr.add(re);
return;
}
}
}
} catch(Exception e) {
LOG.error("把查询条件加入Criteria中出错",e);
}
}
/**
* 把排序条件放入Criteria中,其中[i][1]为一个boolean,true表示升序,false表示降序,[i][0]为排序条件
*
* @param cr
* @param order
* @author 杨浚
*/
private void addCriteriaOrder(Criteria cr,Object[][] order) {
for(int i = 0; i < order.length; i++) {
cr.addOrder((Boolean)order[i][1]?Order.asc((String)order[i][0]):Order.desc((String)order[i][0]));
}
}
/**
* 根据多种混合的条件(如大于,等于,小于,不等于,包含)获得结果总数
*
* @param conditionList
* @return
* @author 杨浚
*/
public long getBeanCountByMultiCondition(final Object[][] conditionList) {
return (Long)getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException,condition);
}
return cr.setProjection(Projections.rowCount()).uniqueResult();
}
});
}
/**
* 根据混合的条件和范围获得结果
* @author 杨浚
* @param conditionList
* @param projectionList
* @param singleResult
* @return
*/
protected T getResultByMultiCondition(final Object[][] conditionList,final Object[] projectionList,final boolean singleResult){
return (T)getHibernateTemplate().executeWithNativeSession(new HibernateCallback(){
public Object doInHibernate(Session sess)
throws HibernateException,sqlException {
Criteria cr=sess.createCriteria(getBean());
for(Object[] condition : conditionList) {
addCriteriaCondition(cr,condition);
}
cr.setProjection(addProjection(cr,projectionList));
if(singleResult){
return cr.uniqueResult();
}else{
return cr.list();
}
}
});
}
/**
* 把查询的范围加入criteria中
* @param cr
* @param projection
*/
private ProjectionList addProjection(Criteria cr,Object[] projection){
ProjectionList pl=Projections.projectionList();
if(projection!=null && projection[0]!=null && !projection[0].equals("")){
try {
Object[] desArray = new Object[projection.length - 1];
System.arraycopy(projection,projection.length - 1);
Class[] classArray=new Class[desArray.length];
for(int i=0;i<desArray.length;i++){
classArray[i]=desArray[i].getClass();
}
Method method = Projections.class.getMethod((String)projection[0],classArray);
Projection p = (Projection) method.invoke(null,desArray);
pl.add(p);
} catch (SecurityException e) {
LOG.error("addProjection("+cr+","+Arrays.toString(projection)+")",e);
} catch (NoSuchMethodException e) {
LOG.error("addProjection("+cr+",e);
} catch (IllegalArgumentException e) {
LOG.error("addProjection("+cr+",e);
} catch (IllegalAccessException e) {
LOG.error("addProjection("+cr+",e);
} catch (InvocationTargetException e) {
LOG.error("addProjection("+cr+",e);
}
}
return pl;
}
/**
* 根据条件得到对象列表
*
* @param eq
* 为null或empty则不判断
* @param currypage
* 小于1则不分页
* @param pagesize
* @param ordername
* 为null或""则不排序
* @param asc
* @return
* @author 华理德
* @date 2009-04-01
*/
protected List<T> getListByEq(Map<String,boolean asc) {
return getListByEqAndIlink(eq,ordername,asc);
}
/**
* 根据条件得到对象列表
*
* @param eq
* 为null或empty则不判断
* @param currypage
* 小于1则不分页
* @param pagesize
* @param ordername
* 为null或length为0则不排序
* @param asc
* @return
* @author 华理德
* @date 2009-04-01
*/
protected List<T> getListByEq(Map<String,String[] ordername,boolean[] asc) {
return getListByEqAndIlink(eq,asc);
}
/**
* 根据条件进行模糊查询
* @param ilinkName
* @param ilinkValue
* @param currypage
* @param pagesize
* @param ordername
* @param asc
* @return
*/
protected List<T> getListByIlink(String name,String value,boolean asc) {
return getListByEqAndIlink(null,getMap(name,value),asc);
}
/**
* 根据条件得到对象列表
*
* @param eq
* 进行相等判断,为null或empty则不判断
* @param ilink
* 进行模糊判断,不区分大小写,为null或empty则不判断
* @param currypage
* 小于1则不分页
* @param pagesize
* @param ordername
* 为null或""则不排序
* @param asc
* @return
* @author 华理德
* @date 2009-04-02
*/
public List<T> getListByEqAndIlink(final Map<String,final String ordername,final boolean asc) {
return getListByEqAndIlink(eq,ilink,(ordername==null||ordername.equals(""))?null:new String[]{ordername},(ordername==null||ordername.equals(""))?null:new boolean[]{asc});
}
public List<T> getListByIlink(Map<String,(ordername==null||ordername.equals(""))?null:new boolean[]{asc});
}
/**
* 根据条件得到对象列表
*
* @param eq
* 进行相等判断,为null或empty则不判断
* @param ilink
* 进行模糊判断,不区分大小写,为null或empty则不判断
* @param currypage
* 小于1则不分页
* @param pagesize
* @param ordername
* 为null或length为0则不排序
* @param asc
* @return
* @author 华理德
* @date 2009-09-23
*/
protected List<T> getListByEqAndIlink(final Map<String,final String[] ordername,final boolean[] asc) {
return getHibernateTemplate().executeFind(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException,sqlException {
Criteria c = session.createCriteria(getBean());
if(eq != null && !eq.isEmpty()) {
c.add(Restrictions.allEq(eq));
}
if(ilink != null && !ilink.isEmpty()) {
for(Iterator<Entry<String,Object>> i = ilink.entrySet().iterator(); i.hasNext();) {
Entry<String,Object> e = i.next();
c.add(Restrictions.ilike(e.getKey(),"%"+ilikePattern.matcher(e.getValue().toString()).replaceAll("\\\\$0")+"%"));
}
}
if(currypage > 0) {
c.setFirstResult((currypage - 1) * pagesize);
c.setMaxResults(pagesize);
}
if(ordername != null && ordername.length>0) {
for(int i = 0; i < ordername.length; i++) {
boolean flag = asc[i];
if(flag) c.addOrder(Order.asc(ordername[i]));
else c.addOrder(Order.desc(ordername[i]));
}
}
return c.list();
}
});
}
protected List<T> getListByEqAndIlink(final Map<String,"%"+ilikePattern.matcher(e.getValue().toString()).replaceAll("\\\\$0")+"%"));
}
}
if(ordername != null && ordername.length>0) {
for(int i = 0; i < ordername.length; i++) {
boolean flag = asc[i];
if(flag) c.addOrder(Order.asc(ordername[i]));
else c.addOrder(Order.desc(ordername[i]));
}
}
return c.list();
}
});
}
/**
* 根据属性得到唯一结果
*
* @param name
* @param value
* @return
*/
protected T getObjectByEq(String name,Object value) {
return getObjectByEq(getMap(name,value));
}
/**
* 根据条件得到唯一结果
*
* @param eq
* @return
*/
protected T getObjectByEq(final Map<String,Object> eq) {
return (T)getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException,sqlException {
Criteria c = session.createCriteria(getBean());
c.add(Restrictions.allEq(eq));
return c.uniqueResult();
}
});
}
/**
* 根据条件得到对象列表
*
* @param name
* 为null或""则不判断
* @param value
* @param currypage
* 小于1则不分页
* @param pagesize
* @param ordername
* 为null或""则不排序
* @param asc
* @return
* @author 华理德
* @date 2009-04-09
*/
protected List<T> getListByEq(String name,Object value,boolean asc) {
return getListByEq(getMap(name,asc);
}
/**
* 根据条件得到对象列表
*
* @param name
* 为null或""则不判断
* @param value
* @param currypage
* 小于1则不分页
* @param pagesize
* @param ordername
* 为null或length为0则不排序
* @param asc
* @return
* @author 华理德
* @date 2009-04-09
*/
protected List<T> getListByEq(String name,boolean[] asc) {
return getListByEq(getMap(name,asc);
}
/**
* 根据条件获取记录数
*
* @param eq
* 为null或empty则不判断
* @return
* @author 华理德
* @date 2009-04-09
*/
protected long getCountByEq(Map<String,Object> eq) {
return getCountByEqAndIlink(eq,null);
}
/**
* 根据条件获取记录数
* @param name
* @param value
* @return
*/
protected long getCountByIlink(String name,String value) {
return getCountByEqAndIlink(null,value));
}
/**
* 根据条件获取记录数
*
* @param eq
* 进行相等判断,为null或empty则不判断
* @param ilink
* 进行模糊判断,不区分大小写,为null或empty则不判断
* @return
* @author 华理德
* @date 2009-04-09
*/
public long getCountByEqAndIlink(final Map<String,Object> ilink) {
return (Long)getHibernateTemplate().executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException,sqlException {
DetachedCriteria dc = DetachedCriteria.forClass(getBean());
if(eq != null && !eq.isEmpty()) {
dc.add(Restrictions.allEq(eq));
}
if(ilink != null && !ilink.isEmpty()) {
for(Iterator<Entry<String,Object> e = i.next();
dc.add(Restrictions.ilike(e.getKey(),"%"+e.getValue()+"%"));
}
}
Criteria c = dc.getExecutableCriteria(session);
c.setProjection(Projections.rowCount());
//Object result = c.uniqueResult();
//return result instanceof Integer?result:Integer.valueOf(((Long)result).intValue());
return c.uniqueResult();
}
});
}
/**
* 根据条件获取记录数
*
* @param name
* 为null或""则不判断
* @param value
* @return
* @author 华理德
* @date 2009-04-09
*/
protected long getCountByEq(String name,Object value) {
return getCountByEq(getMap(name,value));
}
/**
* 保存对象
*
* @param obj
* @author 华理德
* @date 2009-04-09
*/
protected void saveObject(T obj) {
getHibernateTemplate().save(obj);
}
/**
* 更新对象
*
* @param obj
* @author 华理德
* @date 2009-04-09
*/
protected void updateObject(T obj) {
getHibernateTemplate().update(obj);
}
/**
* 删除对象
*
* @param obj
* @author 华理德
* @date 2009-04-09
*/
protected void deleteObject(T obj) {
getHibernateTemplate().delete(obj);
}
/**
* 根据条件删除对象
*
* @param name
* @param value
* @return 删除的记录数
* @author 华理德
* @date 2009-04-09
*/
protected int deleteObject(String name,Object value) {
if(value instanceof List) {
return deleteObject(name,(List)value);
} else {
List<Object> list = new ArrayList<Object>();
list.add(value);
return deleteObject(name,list);
}
}
/**
* 根据条件删除对象
*
* @param name
* @param value
* 为null或empty则不处理
* @return 删除的记录数
* @author 华理德
* @date 2009-04-09
*/
protected int deleteObject(final String name,final List<Object> value) {
if(value == null || value.isEmpty()) {
return 0;
} else {
return (Integer)getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException,sqlException {
String hql = "delete " + getBean().getName() + " where " + name + " in (:value)";
Query query = session.createQuery(hql.toString());
query.setParameterList("value",value);
return query.executeUpdate();
}
});
}
}
/**
* 根据条件删除对象
*
* @param name
* @param value
* 为null或empty则不处理
* @return 删除的记录数
* @author 华理德
* @date 2009-07-28
*/
protected int deleteObject(final String name,final Object[] value) {
if(value == null || value.length == 0) {
return 0;
} else {
return deleteObject(name,Arrays.asList(value));
}
}
/**
* 根据条件得到对象列表
*
* @param name
* @param values
* 进行匹配判断,为null或empty则直接返回空List
* @param currypage
* 小于1则不分页
* @param pagesize
* @param ordername
* 为null或""则不排序
* @param asc
* @return
* @author 华理德
* @date 2009-07-29
*/
protected List<T> getListByIn(String name,Collection values,boolean asc) {
return getListByIn(name,values,(ordername==null||ordername.equals(""))?null:new boolean[]{asc});
}
/**
* 根据条件得到对象列表
*
* @param name
* @param values
* 进行匹配判断,为null或empty则直接返回空List
* @param currypage
* 小于1则不分页
* @param pagesize
* @param ordername
* 为null或length为0则不排序
* @param asc
* @return
* @author 华理德
* @date 2009-09-23
*/
protected List<T> getListByIn(final String name,final Collection values,final boolean[] asc) {
if(values == null || values.isEmpty()) return new ArrayList();
return getHibernateTemplate().executeFind(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException,sqlException {
Criteria c = session.createCriteria(getBean());
c.add(Restrictions.in(name,values));
if(currypage > 0) {
c.setFirstResult((currypage - 1) * pagesize);
c.setMaxResults(pagesize);
}
if(ordername != null && ordername.length>0) {
for(int i = 0; i < ordername.length; i++) {
boolean flag = asc[i];
if(flag) c.addOrder(Order.asc(ordername[i]));
else c.addOrder(Order.desc(ordername[i]));
}
}
return c.list();
}
});
}
/**
* 根据条件查找记录的总数
* @param param
* @param value
* @return
*/
public int getBeanCountByIn(final String param,final Collection value){
if(value ==null || value.isEmpty()){return 0;}
return (Integer)getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session sess)
throws HibernateException,sqlException {
Criteria c = sess.createCriteria(getBean());
c.add(Restrictions.in(param,value));
return c.setProjection(Projections.rowCount()).uniqueResult();
}
});
}
/**
* 根据条件查找记录
* @param param
* @param value
* @return
*/
public List<T> getBeanListByIn(String param,Collection value){
return getListByIn(param,value,null);
}
/**
* 根据条件查找记录并分页
* @param param
* @param value
* @param cpage
* @param pagesize
* @return
*/
public List<T> getBeanListByIn(String param,int pagesize){
return getListByIn(param,cpage,"sid",false);
}
/**
* 根据条件查找记录并按照条件排序
* @param param
* @param value
* @param cpage
* @param pagesize
* @param Order
* @param asc
* @return
*/
public List<T> getBeanListByIn(String param,boolean asc){
return getListByIn(param,asc);
}
/*
* =======================================================================
* 提供给本类处理的私有方法
* =======================================================================
*/
/**
* 根据条件返回Map
*
* @param name
* @param value
* @return name为null或""则返回null
*/
private Map<String,Object> getMap(String name,Object value) {
if(name != null && !name.equals("")) {
Map<String,Object> hs = new HashMap<String,Object>();
hs.put(name,value);
return hs;
}
return null;
}
}
web.xml的配置
<context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:application-*.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 扫描xml配置文件 </listener> <servlet> <servlet-name>spring</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-servlet.xml</param-value> </init-param> <load-on-startup>0</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>/static/*</url-pattern> </servlet-mapping> <servlet> <servlet-name>dwr</servlet-name> <servlet-class>org.directwebremoting.spring.DwrSpringServlet</servlet-class> <init-param> <param-name>debug</param-name> <param-value>true</param-value> </init-param> <init-param> <param-name>crossDomainSessionSecurity</param-name> <param-value>false</param-value> </init-param> <init-param> <param-name>allowScriptTagRemoting</param-name> <param-value>true</param-value> </init-param> <load-on-startup>0</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dwr</servlet-name> <url-pattern>/dwr/*</url-pattern> </servlet-mapping> <servlet> <servlet-name>freemarker</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:ftl-servlet.xml</param-value> </init-param> <load-on-startup>0</load-on-startup> </servlet> <servlet-mapping> <servlet-name>freemarker</servlet-name> <url-pattern>/ftl/*</url-pattern> </servlet-mapping> <servlet> <servlet-name>error</servlet-name> <servlet-class>com.guu.uurms.servlet.ErrorServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>error</servlet-name> <url-pattern>/error</url-pattern> </servlet-mapping> <filter> <filter-name>ftl</filter-name> <filter-class>com.guu.uurms.filter.FreemarkerFilter</filter-class> </filter> <filter-mapping> <filter-name>ftl</filter-name> <url-pattern>*.ftl</url-pattern> </filter-mapping> <filter> <filter-name>controller</filter-name> <filter-class>com.guu.uurms.filter.ControllerFilter</filter-class> </filter> <filter-mapping> <filter-name>controller</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <error-page> <error-code>404</error-code> <location>/error</location> </error-page> <error-page> <error-code>500</error-code> <location>/error</location> </error-page> <welcome-file-list> <welcome-file>index.ftl</welcome-file> </welcome-file-list> </web-app>
原文链接:https://www.f2er.com/springmvc/164307.html