分为几个部分
1.工具集合 utils
2.测试 test
3.orm-hibernate扩展
4.web-struts2的扩展
5.webservice接口
首先先看工具类集合先吧
1.工具集合 utils
Java代码package org.springside.modules.utils;
import java.lang.reflect.Field;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
public class BeanUtils
{
protected static Logger logger = LoggerFactory.getLogger(BeanUtils.class);
public static Object getFieldValue(Object object, String fieldName)
throws NoSuchFieldException
{
Field field = getDeclaredField(object, fieldName);
if (!(field.isAccessible())) {
field.setAccessible(true);
}
Object result = null;
try {
result = field.get(object);
} catch (IllegalAccessException e) {
logger.error("不可能抛出的异常{}", e.getMessage());
}
return result;
}
public static void setFieldValue(Object object, String fieldName, Object value)
throws NoSuchFieldException
{
Field field = getDeclaredField(object, fieldName);
if (!(field.isAccessible()))
field.setAccessible(true);
try
{
field.set(object, value);
} catch (IllegalAccessException e) {
logger.error("不可能抛出的异常:{}", e.getMessage());
}
}
public static Field getDeclaredField(Object object, String fieldName)
throws NoSuchFieldException
{
Assert.notNull(object);
return getDeclaredField(object.getClass(), fieldName);
}
public static Field getDeclaredField(Class clazz, String fieldName) throws NoSuchFieldException
{
Assert.notNull(clazz);
Assert.hasText(fieldName);
Class superClass = clazz; if (superClass != Object.class);
try
{
return superClass.getDeclaredField(fieldName);
}
catch (NoSuchFieldException e)
{
while (true) {
superClass = superClass.getSuperclass();
}
throw new NoSuchFieldException("No such field: " + clazz.getName() + '.' + fieldName);
}
}
}
Java代码
package org.springside.modules.utils;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.StringUtils;
public class CollectionUtils
{
public static List fetchPropertyToList(Collection collection, String propertyName)
throws Exception
{
List list = new ArrayList();
for (Iterator i$ = collection.iterator(); i$.hasNext(); ) { Object obj = i$.next();
list.add(PropertyUtils.getProperty(obj, propertyName));
}
return list;
}
public static String fetchPropertyToString(Collection collection, String propertyName, String separator)
throws Exception
{
List list = fetchPropertyToList(collection, propertyName);
return StringUtils.join(list, separator);
}
public static <T, ID> void mergeByCheckedIds(Collection<T> collection, Collection<ID> checkedIds, Class<T> clazz)
throws Exception
{
mergeByCheckedIds(collection, checkedIds, "id", clazz);
}
public static <T, ID> void mergeByCheckedIds(Collection<T> collection, Collection<ID> checkedIds, String idName, Class<T> clazz)
throws Exception
{
if (checkedIds == null) {
collection.clear();
return;
}
Iterator it = collection.iterator();
while (it.hasNext()) {
Object obj = it.next();
if (checkedIds.contains(PropertyUtils.getProperty(obj, idName)))
checkedIds.remove(PropertyUtils.getProperty(obj, idName));
else
it.remove();
}
for (Iterator i$ = checkedIds.iterator(); i$.hasNext(); ) { Object id = i$.next();
Object obj = clazz.newInstance();
PropertyUtils.setProperty(obj, idName, id);
collection.add(obj);
}
}
}
Java代码
package org.springside.modules.utils;
import net.sf.dozer.util.mapping.DozerBeanMapper;
import net.sf.dozer.util.mapping.MapperIF;
public final class DozerMapperSingleton
{
private static MapperIF instance;
public static synchronized MapperIF getInstance()
{
if (instance == null)
instance = new DozerBeanMapper();
return instance;
}
}
Java代码package org.springside.modules.utils;
import javax.annotation.PostConstruct;
import org.slf4j.bridge.SLF4JBridgeHandler;
public class JulOverSlf4jProcessor
{
@PostConstruct
public void init()
{
SLF4JBridgeHandler.install();
}
}
2.测试 test
Java代码
package org.springside.modules.test;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit38.AbstractJUnit38SpringContextTests;
@ContextConfiguration(locations={"/applicationContext.xml"})
public class SpringTestCase extends AbstractJUnit38SpringContextTests
{
}
Java代码
package org.springside.modules.test;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit38.AbstractTransactionalJUnit38SpringContextTests;
@ContextConfiguration(locations={"/applicationContext.xml"})
public class SpringTransactionalTestCase extends AbstractTransactionalJUnit38SpringContextTests
{
public void flush()
{
flush("sessionFactory");
}
public void flush(String sessionFactoryName)
{
((SessionFactory)this.applicationContext.getBean(sessionFactoryName)).getCurrentSession().flush();
}
}3.orm-hibernate扩展
Java代码
package org.springside.modules.orm.hibernate;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projection;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.impl.CriteriaImpl;
import org.hibernate.transform.ResultTransformer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
import org.springside.modules.utils.BeanUtils;
public class SimpleHibernateTemplate<T, PK extends Serializable>
{
protected Logger logger = LoggerFactory.getLogger(super.getClass());
protected SessionFactory sessionFactory;
protected Class<T> entityClass;
public SimpleHibernateTemplate(SessionFactory sessionFactory, Class<T> entityClass)
{
this.sessionFactory = sessionFactory;
this.entityClass = entityClass;
}
public Session getSession() {
return this.sessionFactory.getCurrentSession();
}
public SessionFactory getSessionFactory() {
return this.sessionFactory;
}
public void save(T entity) {
Assert.notNull(entity);
getSession().saveOrUpdate(entity);
this.logger.info("save entity: {}", entity);
}
public void delete(T entity) {
Assert.notNull(entity);
getSession().delete(entity);
this.logger.info("delete entity: {}", entity);
}
public void delete(PK id) {
Assert.notNull(id);
delete(get(id));
}
public List<T> findAll() {
return findByCriteria(new Criterion[0]);
}
public Page<T> findAll(Page<T> page) {
return findByCriteria(page, new Criterion[0]);
}
public T get(PK id)
{
return getSession().load(this.entityClass, id);
}
public List find(String hql, Object[] values)
{
return createQuery(hql, values).list();
}
public Page<T> find(Page<T> page, String hql, Object[] values)
{
Assert.notNull(page);
if (page.isAutoCount())
this.logger.warn("HQL查询暂不支持自动获取总结果数,hql为{}", hql);
Query q = createQuery(hql, values);
if (page.isFirstSetted())
q.setFirstResult(page.getFirst());
if (page.isPageSizeSetted())
q.setMaxResults(page.getPageSize());
page.setResult(q.list());
return page;
}
public Object findUnique(String hql, Object[] values)
{
return createQuery(hql, values).uniqueResult();
}
public Integer findInt(String hql, Object[] values)
{
return ((Integer)findUnique(hql, values));
}
public Long findLong(String hql, Object[] values)
{
return ((Long)findUnique(hql, values));
}
public List<T> findByCriteria(Criterion[] criterion)
{
return createCriteria(criterion).list();
}
public Page<T> findByCriteria(Page page, Criterion[] criterion)
{
Assert.notNull(page);
Criteria c = createCriteria(criterion);
if (page.isAutoCount())
page.setTotalCount(countQueryResult(page, c));
if (page.isFirstSetted())
c.setFirstResult(page.getFirst());
if (page.isPageSizeSetted()) {
c.setMaxResults(page.getPageSize());
}
if (page.isOrderBySetted())
if (page.getOrder().endsWith("asc"))
c.addOrder(Order.asc(page.getOrderBy()));
else
c.addOrder(Order.desc(page.getOrderBy()));
page.setResult(c.list());
return page;
}
public List<T> findByProperty(String propertyName, Object value)
{
Assert.hasText(propertyName);
return createCriteria(new Criterion[] { Restrictions.eq(propertyName, value) }).list();
}
public T findUniqueByProperty(String propertyName, Object value)
{
Assert.hasText(propertyName);
return createCriteria(new Criterion[] { Restrictions.eq(propertyName, value) }).uniqueResult();
}
public Query createQuery(String queryString, Object[] values)
{
Assert.hasText(queryString);
Query queryObject = getSession().createQuery(queryString);
if (values != null)
for (int i = 0; i < values.length; ++i)
queryObject.setParameter(i, values[i]);
return queryObject;
}
public Criteria createCriteria(Criterion[] criterions)
{
Criteria criteria = getSession().createCriteria(this.entityClass);
Criterion[] arr$ = criterions; int len$ = arr$.length; for (int i$ = 0; i$ < len$; ++i$) { Criterion c = arr$[i$];
criteria.add(c);
}
return criteria;
}
public boolean isPropertyUnique(String propertyName, Object newValue, Object orgValue)
{
if ((newValue == null) || (newValue.equals(orgValue)))
return true;
Object object = findUniqueByProperty(propertyName, newValue);
return (object == null);
}
protected int countQueryResult(Page<T> page, Criteria c)
{
CriteriaImpl impl = (CriteriaImpl)c;
Projection projection = impl.getProjection();
ResultTransformer transformer = impl.getResultTransformer();
List orderEntries = null;
try {
orderEntries = (List)BeanUtils.getFieldValue(impl, "orderEntries");
BeanUtils.setFieldValue(impl, "orderEntries", new ArrayList());
} catch (Exception e) {
this.logger.error("不可能抛出的异常:{}", e.getMessage());
}
int totalCount = ((Integer)c.setProjection(Projections.rowCount()).uniqueResult()).intValue();
if (totalCount < 1) {
return -1;
}
c.setProjection(projection);
if (projection == null)
c.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
if (transformer != null)
c.setResultTransformer(transformer);
try
{
BeanUtils.setFieldValue(impl, "orderEntries", orderEntries);
} catch (Exception e) {
this.logger.error("不可能抛出的异常:{}", e.getMessage());
}
return totalCount;
}
}
Java代码
package org.springside.modules.orm.hibernate;
import org.apache.commons.lang.StringUtils;
public class QueryParameter
{
public static final String ASC = "asc";
public static final String DESC = "desc";
protected int pageNo;
protected int pageSize;
protected String orderBy;
protected String order;
protected boolean autoCount;
public QueryParameter()
{
this.pageNo = 1;
this.pageSize = -1;
this.orderBy = null;
this.order = "asc";
this.autoCount = false;
}
public int getPageSize()
{
return this.pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public boolean isPageSizeSetted()
{
return (this.pageSize > -1);
}
public int getPageNo()
{
return this.pageNo;
}
public void setPageNo(int pageNo) {
this.pageNo = pageNo;
}
public int getFirst()
{
if ((this.pageNo < 1) || (this.pageSize < 1))
return -1;
return ((this.pageNo - 1) * this.pageSize);
}
public boolean isFirstSetted()
{
return ((this.pageNo > 0) && (this.pageSize > 0));
}
public String getOrderBy()
{
return this.orderBy;
}
public void setOrderBy(String orderBy) {
this.orderBy = orderBy;
}
public boolean isOrderBySetted()
{
return StringUtils.isNotBlank(this.orderBy);
}
public String getOrder()
{
return this.order;
}
public void setOrder(String order)
{
if (("asc".equalsIgnoreCase(order)) || ("desc".equalsIgnoreCase(order)))
this.order = order.toLowerCase();
else
throw new IllegalArgumentException("order should be 'desc' or 'asc'");
}
public boolean isAutoCount()
{
return this.autoCount;
}
public void setAutoCount(boolean autoCount) {
this.autoCount = autoCount;
}
}
Java代码
package org.springside.modules.orm.hibernate;
import java.util.List;
public class Page<T> extends QueryParameter
{
private List<T> result = null;
private int totalCount = -1;
public Page()
{
}
public Page(int pageSize)
{
this.pageSize = pageSize;
}
public Page(int pageSize, boolean autoCount) {
this.pageSize = pageSize;
this.autoCount = autoCount;
}
public String getInverseOrder()
{
if (this.order.endsWith("desc"))
return "asc";
return "desc";
}
public List<T> getResult()
{
return this.result;
}
public void setResult(List<T> result) {
this.result = result;
}
public int getTotalCount()
{
return this.totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
public int getTotalPages()
{
if (this.totalCount == -1)
return -1;
int count = this.totalCount / this.pageSize;
if (this.totalCount % this.pageSize > 0)
++count;
return count;
}
public boolean isHasNext()
{
return (this.pageNo + 1 <= getTotalPages());
}
public int getNextPage()
{
if (isHasNext())
return (this.pageNo + 1);
return this.pageNo;
}
public boolean isHasPre()
{
return (this.pageNo - 1 >= 1);
}
public int getPrePage()
{
if (isHasPre())
return (this.pageNo - 1);
return this.pageNo;
}
}
接着是stuts2
Java代码
package org.springside.modules.web.struts2;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;
public abstract class CRUDActionSupport<T> extends SimpleActionSupport
implements ModelDriven<T>, Preparable
{
public static final String RELOAD = "reload";
public String execute()
throws Exception
{
return list();
}
public abstract String list()
throws Exception;
public abstract String save()
throws Exception;
public abstract String delete()
throws Exception;
public void prepareSave()
throws Exception
{
prepareModel();
}
public void prepareInput()
throws Exception
{
prepareModel();
}
public void prepare()
throws Exception
{
}
protected abstract void prepareModel()
throws Exception;
}
Java代码
package org.springside.modules.web.struts2;
import com.opensymphony.xwork2.ActionSupport;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SimpleActionSupport extends ActionSupport
{
protected final Logger logger;
public SimpleActionSupport()
{
this.logger = LoggerFactory.getLogger(getClass());
}
protected String render(String text, String contentType)
{
HttpServletResponse response;
try {
response = ServletActionContext.getResponse();
response.setContentType(contentType);
response.getWriter().write(text);
} catch (IOException e) {
this.logger.error(e.getMessage(), e);
}
return null;
}
protected String renderText(String text)
{
return render(text, "text/plain;charset=UTF-8");
}
protected String renderHtml(String html)
{
return render(html, "text/html;charset=UTF-8");
}
protected String renderXML(String xml)
{
return render(xml, "text/xml;charset=UTF-8");
}
}
最后是webservice
Java代码
package org.springside.modules.webservice;
import javax.annotation.PostConstruct;
import net.sf.dozer.util.mapping.MapperIF;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springside.modules.utils.DozerMapperSingleton;
public abstract class WebServiceSupport
{
protected final Logger logger;
protected MapperIF dozer;
public WebServiceSupport()
{
this.logger = LoggerFactory.getLogger(super.getClass());
}
public void setDozer(MapperIF dozer)
{
this.dozer = dozer;
}
@PostConstruct
public void initDozer()
{
if (this.dozer == null) {
this.logger.info("ApplicationContext中不存在dozer mapper,使用无配置文件的默认dozer.");
this.dozer = DozerMapperSingleton.getInstance();
}
}
}最后总结:个人觉得测试那块的配置尚需完善。
评论
1 楼 kenter1643 2009-03-03 引用
Spring配置
Java代码 <?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:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"
default-lazy-init="true">
<description>Spring公共配置文件</description>
<!-- 定义受环境影响易变的变量 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName"
value="com.mysql.jdbc.Driver">
</property>
<property name="url" value="jdbc:mysql://localhost:3306/test"></property>
<property name="username" value="root"></property>
<property name="password" value="manager"></property>
</bean>
<!--初始化-->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>com.kentertest.entity.Tablename1</value>
</list>
</property>
</bean>
<!--事务管理-->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!--自导扫描存在的service-->
<context:component-scan base-package="com.kentertest.service" />
<!--自动事务管理-->
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
1.工具集合 utils
2.测试 test
3.orm-hibernate扩展
4.web-struts2的扩展
5.webservice接口
首先先看工具类集合先吧
1.工具集合 utils
Java代码package org.springside.modules.utils;
import java.lang.reflect.Field;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
public class BeanUtils
{
protected static Logger logger = LoggerFactory.getLogger(BeanUtils.class);
public static Object getFieldValue(Object object, String fieldName)
throws NoSuchFieldException
{
Field field = getDeclaredField(object, fieldName);
if (!(field.isAccessible())) {
field.setAccessible(true);
}
Object result = null;
try {
result = field.get(object);
} catch (IllegalAccessException e) {
logger.error("不可能抛出的异常{}", e.getMessage());
}
return result;
}
public static void setFieldValue(Object object, String fieldName, Object value)
throws NoSuchFieldException
{
Field field = getDeclaredField(object, fieldName);
if (!(field.isAccessible()))
field.setAccessible(true);
try
{
field.set(object, value);
} catch (IllegalAccessException e) {
logger.error("不可能抛出的异常:{}", e.getMessage());
}
}
public static Field getDeclaredField(Object object, String fieldName)
throws NoSuchFieldException
{
Assert.notNull(object);
return getDeclaredField(object.getClass(), fieldName);
}
public static Field getDeclaredField(Class clazz, String fieldName) throws NoSuchFieldException
{
Assert.notNull(clazz);
Assert.hasText(fieldName);
Class superClass = clazz; if (superClass != Object.class);
try
{
return superClass.getDeclaredField(fieldName);
}
catch (NoSuchFieldException e)
{
while (true) {
superClass = superClass.getSuperclass();
}
throw new NoSuchFieldException("No such field: " + clazz.getName() + '.' + fieldName);
}
}
}
Java代码
package org.springside.modules.utils;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.StringUtils;
public class CollectionUtils
{
public static List fetchPropertyToList(Collection collection, String propertyName)
throws Exception
{
List list = new ArrayList();
for (Iterator i$ = collection.iterator(); i$.hasNext(); ) { Object obj = i$.next();
list.add(PropertyUtils.getProperty(obj, propertyName));
}
return list;
}
public static String fetchPropertyToString(Collection collection, String propertyName, String separator)
throws Exception
{
List list = fetchPropertyToList(collection, propertyName);
return StringUtils.join(list, separator);
}
public static <T, ID> void mergeByCheckedIds(Collection<T> collection, Collection<ID> checkedIds, Class<T> clazz)
throws Exception
{
mergeByCheckedIds(collection, checkedIds, "id", clazz);
}
public static <T, ID> void mergeByCheckedIds(Collection<T> collection, Collection<ID> checkedIds, String idName, Class<T> clazz)
throws Exception
{
if (checkedIds == null) {
collection.clear();
return;
}
Iterator it = collection.iterator();
while (it.hasNext()) {
Object obj = it.next();
if (checkedIds.contains(PropertyUtils.getProperty(obj, idName)))
checkedIds.remove(PropertyUtils.getProperty(obj, idName));
else
it.remove();
}
for (Iterator i$ = checkedIds.iterator(); i$.hasNext(); ) { Object id = i$.next();
Object obj = clazz.newInstance();
PropertyUtils.setProperty(obj, idName, id);
collection.add(obj);
}
}
}
Java代码
package org.springside.modules.utils;
import net.sf.dozer.util.mapping.DozerBeanMapper;
import net.sf.dozer.util.mapping.MapperIF;
public final class DozerMapperSingleton
{
private static MapperIF instance;
public static synchronized MapperIF getInstance()
{
if (instance == null)
instance = new DozerBeanMapper();
return instance;
}
}
Java代码package org.springside.modules.utils;
import javax.annotation.PostConstruct;
import org.slf4j.bridge.SLF4JBridgeHandler;
public class JulOverSlf4jProcessor
{
@PostConstruct
public void init()
{
SLF4JBridgeHandler.install();
}
}
2.测试 test
Java代码
package org.springside.modules.test;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit38.AbstractJUnit38SpringContextTests;
@ContextConfiguration(locations={"/applicationContext.xml"})
public class SpringTestCase extends AbstractJUnit38SpringContextTests
{
}
Java代码
package org.springside.modules.test;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit38.AbstractTransactionalJUnit38SpringContextTests;
@ContextConfiguration(locations={"/applicationContext.xml"})
public class SpringTransactionalTestCase extends AbstractTransactionalJUnit38SpringContextTests
{
public void flush()
{
flush("sessionFactory");
}
public void flush(String sessionFactoryName)
{
((SessionFactory)this.applicationContext.getBean(sessionFactoryName)).getCurrentSession().flush();
}
}3.orm-hibernate扩展
Java代码
package org.springside.modules.orm.hibernate;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projection;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.impl.CriteriaImpl;
import org.hibernate.transform.ResultTransformer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
import org.springside.modules.utils.BeanUtils;
public class SimpleHibernateTemplate<T, PK extends Serializable>
{
protected Logger logger = LoggerFactory.getLogger(super.getClass());
protected SessionFactory sessionFactory;
protected Class<T> entityClass;
public SimpleHibernateTemplate(SessionFactory sessionFactory, Class<T> entityClass)
{
this.sessionFactory = sessionFactory;
this.entityClass = entityClass;
}
public Session getSession() {
return this.sessionFactory.getCurrentSession();
}
public SessionFactory getSessionFactory() {
return this.sessionFactory;
}
public void save(T entity) {
Assert.notNull(entity);
getSession().saveOrUpdate(entity);
this.logger.info("save entity: {}", entity);
}
public void delete(T entity) {
Assert.notNull(entity);
getSession().delete(entity);
this.logger.info("delete entity: {}", entity);
}
public void delete(PK id) {
Assert.notNull(id);
delete(get(id));
}
public List<T> findAll() {
return findByCriteria(new Criterion[0]);
}
public Page<T> findAll(Page<T> page) {
return findByCriteria(page, new Criterion[0]);
}
public T get(PK id)
{
return getSession().load(this.entityClass, id);
}
public List find(String hql, Object[] values)
{
return createQuery(hql, values).list();
}
public Page<T> find(Page<T> page, String hql, Object[] values)
{
Assert.notNull(page);
if (page.isAutoCount())
this.logger.warn("HQL查询暂不支持自动获取总结果数,hql为{}", hql);
Query q = createQuery(hql, values);
if (page.isFirstSetted())
q.setFirstResult(page.getFirst());
if (page.isPageSizeSetted())
q.setMaxResults(page.getPageSize());
page.setResult(q.list());
return page;
}
public Object findUnique(String hql, Object[] values)
{
return createQuery(hql, values).uniqueResult();
}
public Integer findInt(String hql, Object[] values)
{
return ((Integer)findUnique(hql, values));
}
public Long findLong(String hql, Object[] values)
{
return ((Long)findUnique(hql, values));
}
public List<T> findByCriteria(Criterion[] criterion)
{
return createCriteria(criterion).list();
}
public Page<T> findByCriteria(Page page, Criterion[] criterion)
{
Assert.notNull(page);
Criteria c = createCriteria(criterion);
if (page.isAutoCount())
page.setTotalCount(countQueryResult(page, c));
if (page.isFirstSetted())
c.setFirstResult(page.getFirst());
if (page.isPageSizeSetted()) {
c.setMaxResults(page.getPageSize());
}
if (page.isOrderBySetted())
if (page.getOrder().endsWith("asc"))
c.addOrder(Order.asc(page.getOrderBy()));
else
c.addOrder(Order.desc(page.getOrderBy()));
page.setResult(c.list());
return page;
}
public List<T> findByProperty(String propertyName, Object value)
{
Assert.hasText(propertyName);
return createCriteria(new Criterion[] { Restrictions.eq(propertyName, value) }).list();
}
public T findUniqueByProperty(String propertyName, Object value)
{
Assert.hasText(propertyName);
return createCriteria(new Criterion[] { Restrictions.eq(propertyName, value) }).uniqueResult();
}
public Query createQuery(String queryString, Object[] values)
{
Assert.hasText(queryString);
Query queryObject = getSession().createQuery(queryString);
if (values != null)
for (int i = 0; i < values.length; ++i)
queryObject.setParameter(i, values[i]);
return queryObject;
}
public Criteria createCriteria(Criterion[] criterions)
{
Criteria criteria = getSession().createCriteria(this.entityClass);
Criterion[] arr$ = criterions; int len$ = arr$.length; for (int i$ = 0; i$ < len$; ++i$) { Criterion c = arr$[i$];
criteria.add(c);
}
return criteria;
}
public boolean isPropertyUnique(String propertyName, Object newValue, Object orgValue)
{
if ((newValue == null) || (newValue.equals(orgValue)))
return true;
Object object = findUniqueByProperty(propertyName, newValue);
return (object == null);
}
protected int countQueryResult(Page<T> page, Criteria c)
{
CriteriaImpl impl = (CriteriaImpl)c;
Projection projection = impl.getProjection();
ResultTransformer transformer = impl.getResultTransformer();
List orderEntries = null;
try {
orderEntries = (List)BeanUtils.getFieldValue(impl, "orderEntries");
BeanUtils.setFieldValue(impl, "orderEntries", new ArrayList());
} catch (Exception e) {
this.logger.error("不可能抛出的异常:{}", e.getMessage());
}
int totalCount = ((Integer)c.setProjection(Projections.rowCount()).uniqueResult()).intValue();
if (totalCount < 1) {
return -1;
}
c.setProjection(projection);
if (projection == null)
c.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
if (transformer != null)
c.setResultTransformer(transformer);
try
{
BeanUtils.setFieldValue(impl, "orderEntries", orderEntries);
} catch (Exception e) {
this.logger.error("不可能抛出的异常:{}", e.getMessage());
}
return totalCount;
}
}
Java代码
package org.springside.modules.orm.hibernate;
import org.apache.commons.lang.StringUtils;
public class QueryParameter
{
public static final String ASC = "asc";
public static final String DESC = "desc";
protected int pageNo;
protected int pageSize;
protected String orderBy;
protected String order;
protected boolean autoCount;
public QueryParameter()
{
this.pageNo = 1;
this.pageSize = -1;
this.orderBy = null;
this.order = "asc";
this.autoCount = false;
}
public int getPageSize()
{
return this.pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public boolean isPageSizeSetted()
{
return (this.pageSize > -1);
}
public int getPageNo()
{
return this.pageNo;
}
public void setPageNo(int pageNo) {
this.pageNo = pageNo;
}
public int getFirst()
{
if ((this.pageNo < 1) || (this.pageSize < 1))
return -1;
return ((this.pageNo - 1) * this.pageSize);
}
public boolean isFirstSetted()
{
return ((this.pageNo > 0) && (this.pageSize > 0));
}
public String getOrderBy()
{
return this.orderBy;
}
public void setOrderBy(String orderBy) {
this.orderBy = orderBy;
}
public boolean isOrderBySetted()
{
return StringUtils.isNotBlank(this.orderBy);
}
public String getOrder()
{
return this.order;
}
public void setOrder(String order)
{
if (("asc".equalsIgnoreCase(order)) || ("desc".equalsIgnoreCase(order)))
this.order = order.toLowerCase();
else
throw new IllegalArgumentException("order should be 'desc' or 'asc'");
}
public boolean isAutoCount()
{
return this.autoCount;
}
public void setAutoCount(boolean autoCount) {
this.autoCount = autoCount;
}
}
Java代码
package org.springside.modules.orm.hibernate;
import java.util.List;
public class Page<T> extends QueryParameter
{
private List<T> result = null;
private int totalCount = -1;
public Page()
{
}
public Page(int pageSize)
{
this.pageSize = pageSize;
}
public Page(int pageSize, boolean autoCount) {
this.pageSize = pageSize;
this.autoCount = autoCount;
}
public String getInverseOrder()
{
if (this.order.endsWith("desc"))
return "asc";
return "desc";
}
public List<T> getResult()
{
return this.result;
}
public void setResult(List<T> result) {
this.result = result;
}
public int getTotalCount()
{
return this.totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
public int getTotalPages()
{
if (this.totalCount == -1)
return -1;
int count = this.totalCount / this.pageSize;
if (this.totalCount % this.pageSize > 0)
++count;
return count;
}
public boolean isHasNext()
{
return (this.pageNo + 1 <= getTotalPages());
}
public int getNextPage()
{
if (isHasNext())
return (this.pageNo + 1);
return this.pageNo;
}
public boolean isHasPre()
{
return (this.pageNo - 1 >= 1);
}
public int getPrePage()
{
if (isHasPre())
return (this.pageNo - 1);
return this.pageNo;
}
}
接着是stuts2
Java代码
package org.springside.modules.web.struts2;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;
public abstract class CRUDActionSupport<T> extends SimpleActionSupport
implements ModelDriven<T>, Preparable
{
public static final String RELOAD = "reload";
public String execute()
throws Exception
{
return list();
}
public abstract String list()
throws Exception;
public abstract String save()
throws Exception;
public abstract String delete()
throws Exception;
public void prepareSave()
throws Exception
{
prepareModel();
}
public void prepareInput()
throws Exception
{
prepareModel();
}
public void prepare()
throws Exception
{
}
protected abstract void prepareModel()
throws Exception;
}
Java代码
package org.springside.modules.web.struts2;
import com.opensymphony.xwork2.ActionSupport;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SimpleActionSupport extends ActionSupport
{
protected final Logger logger;
public SimpleActionSupport()
{
this.logger = LoggerFactory.getLogger(getClass());
}
protected String render(String text, String contentType)
{
HttpServletResponse response;
try {
response = ServletActionContext.getResponse();
response.setContentType(contentType);
response.getWriter().write(text);
} catch (IOException e) {
this.logger.error(e.getMessage(), e);
}
return null;
}
protected String renderText(String text)
{
return render(text, "text/plain;charset=UTF-8");
}
protected String renderHtml(String html)
{
return render(html, "text/html;charset=UTF-8");
}
protected String renderXML(String xml)
{
return render(xml, "text/xml;charset=UTF-8");
}
}
最后是webservice
Java代码
package org.springside.modules.webservice;
import javax.annotation.PostConstruct;
import net.sf.dozer.util.mapping.MapperIF;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springside.modules.utils.DozerMapperSingleton;
public abstract class WebServiceSupport
{
protected final Logger logger;
protected MapperIF dozer;
public WebServiceSupport()
{
this.logger = LoggerFactory.getLogger(super.getClass());
}
public void setDozer(MapperIF dozer)
{
this.dozer = dozer;
}
@PostConstruct
public void initDozer()
{
if (this.dozer == null) {
this.logger.info("ApplicationContext中不存在dozer mapper,使用无配置文件的默认dozer.");
this.dozer = DozerMapperSingleton.getInstance();
}
}
}最后总结:个人觉得测试那块的配置尚需完善。
评论
1 楼 kenter1643 2009-03-03 引用
Spring配置
Java代码 <?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:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"
default-lazy-init="true">
<description>Spring公共配置文件</description>
<!-- 定义受环境影响易变的变量 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName"
value="com.mysql.jdbc.Driver">
</property>
<property name="url" value="jdbc:mysql://localhost:3306/test"></property>
<property name="username" value="root"></property>
<property name="password" value="manager"></property>
</bean>
<!--初始化-->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>com.kentertest.entity.Tablename1</value>
</list>
</property>
</bean>
<!--事务管理-->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!--自导扫描存在的service-->
<context:component-scan base-package="com.kentertest.service" />
<!--自动事务管理-->
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>