源码下载:http://download.csdn.net/download/knight_black_bob/9332831
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>sshdemo</display-name> <!-- spring --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <context-param> <param-name>eccache</param-name> <param-value>ehcache.xml</param-value> </context-param> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>*.html</url-pattern> </filter-mapping> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>*.jsp</url-pattern> </filter-mapping> <!-- 防止spring内存溢出监听器 --> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- spring监听器,使用scrope=request 时必须加上 --> <listener> <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class> </listener> <!-- struts2 --> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>*.html</url-pattern> </filter-mapping> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>*.jsp</url-pattern> </filter-mapping> <session-config> <session-timeout>120</session-timeout> </session-config> <error-page> <error-code>401</error-code> <location>/error/401.jsp</location> </error-page> <error-page> <error-code>403</error-code> <location>/error/403.jsp</location> </error-page> <error-page> <error-code>404</error-code> <location>/error/404.jsp</location> </error-page> <error-page> <error-code>500</error-code> <location>/error/error.jsp</location> </error-page> <welcome-file-list> <welcome-file>/welcome.jsp</welcome-file> </welcome-file-list> </web-app>
applicationContext.xml
<?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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd" default-lazy-init="false"> <!-- 导入properties --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:jdbc.properties</value> </list> </property> </bean> <!--数据源配置 --> <bean id="dataSource" class="org.logicalcobwebs.proxool.ProxoolDataSource"> <property name="driver" value="${db.driver}"/> <property name="driverUrl" value="${db.url}"/> <property name="user" value="${db.user}"/> <property name="password" value="${db.password}"/> <!-- <property name="alias" value="${db.alias}"/> --> <property name="houseKeepingTestSql" value="select 1" /> <property name="houseKeepingSleepTime" value="90000" /> <property name="minimumConnectionCount" value="${db.minimumConnectionCount}"/> <property name="maximumConnectionCount" value="${db.maximumConnectionCount}"/> <property name="maximumActiveTime" value="${db.maximumActiveTime}" /> <property name="maximumConnectionLifetime" value="${db.maximumConnectionLifetime}" /> <property name="testBeforeUse" value="true" /> <property name="delegateProperties" value="characterEncoding=${db.characterEncoding}"/> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource"> <ref bean="dataSource" /> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> org.hibernate.dialect.MySQL5Dialect </prop> <!-- 显示运行时的sql语句 --> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.hbm2ddl.auto">none</prop> <!-- 设置一次最多提交的sql语句上限,Fetch Size设的越大,读数据库的次数 越少,速度越快;Fetch Size越小,读数据库的次数越多,速度越慢。 --> <prop key="hibernate.jdbc.batch_size">50</prop> <prop key="hibernate.cache.use_query_cache">true</prop> <prop key="hibernate.cache.use_second_level_cache">true</prop> <prop key="hibernate.cache.provider_class">net.sf.ehcache.hibernate.EhCacheProvider</prop> <prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop> <prop key="hibernate.cache.provider_configuration_file_resource_path">ehcache.xml</prop> <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</prop> </props> </property> <property name="packagesToScan"> <list> <value>com.baoy.cn</value> </list> </property> </bean> <!-- 事务配置 --> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory"> <ref local="sessionFactory"/> </property> </bean> <!-- 使用annotation定义事务 --> <tx:annotation-driven transaction-manager="transactionManager"/> <context:component-scan base-package="com.baoy.cn"></context:component-scan> </beans>
struts.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <constant name="struts.devMode" value="true" /> <constant name="struts.enable.DynamicMethodInvocation" value="false" /> <constant name="struts.i18n.encoding" value="UTF-8" /> <constant name="struts.ui.theme" value="simple" /> <constant name="struts.multipart.maxSize" value="512102400" /> <constant name="struts.action.extension" value="html" /> <package name="exceptionPackage" namespace="/" extends="struts-default"> <interceptors> <interceptor name="authInterceptor" class="com.baoy.cn.core.AuthInterceptor"></interceptor> <interceptor name="trimInterceptor" class="trimInterceptor" /> <interceptor name="exceptionInterceptor" class="exceptionInterceptor" /> <interceptor-stack name="nosessionStack"> <interceptor-ref name="defaultStack" /> </interceptor-stack> </interceptors> <default-interceptor-ref name="nosessionStack"></default-interceptor-ref> <global-results> <result name="login" type="redirect">/user/login.jsp</result> <result name="error" type="redirect">/user/error.jsp</result> <result name="error-500" type="redirect">/user/error.jsp</result> </global-results> <global-exception-mappings> <exception-mapping exception="java.lang.Exception" result="error-500"/> </global-exception-mappings> </package> <include file="struts-*.xml"/> </struts>
struts-action-user.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <package name="actionpackage" extends="exceptionPackage" namespace="/"> <action name="userAction_*" class="userAction" method="{1}"> <result name="findall" >/user/list.jsp</result> <result name="toadd">/user/add.jsp</result> <result name="adduser-error" type="redirect">/userAction_addUser.html</result> <result name="adduser-success" type="redirect">/userAction_findAllUser.html</result> <result name="deleteuser" type="redirect">/userAction_findAllUser.html</result> <result name="toedit">/user/edit.jsp</result> <result name="updateuser-error" type="redirect">/userAction_toEdit.html?id=${id}</result> <result name="updateuser-success" type="redirect">/userAction_findAllUser.html</result> </action> </package> </struts>
jdbc.properties
db.driver=com.mysql.jdbc.Driver db.url=jdbc:mysql://localhost:3306/database?useUnicode=true&characterEncoding=utf-8 db.user=root db.password=root db.minimumConnectionCount=5 db.maximumConnectionCount=50 db.maximumActiveTime=36000000 db.maximumConnectionLifetime=36000000 db.characterEncoding=utf-8
UserAction
package com.baoy.cn.action; import java.util.List; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import com.baoy.cn.bean.User; import com.baoy.cn.core.BaseAction; import com.baoy.cn.service.UserService; /** * @author baoyou E-mail:[email protected] * @version 创建时间:2015年12月5日 下午10:34:06 * des: */ @Scope("prototype") @Controller("userAction") public class UserAction extends BaseAction{ private static final long serialVersionUID = 1L; private static final Logger log = Logger.getLogger(UserAction.class); @Autowired UserService userService; private User user; private int id; //url: http://localhost:8080/sshdemo/userAction_findAllUser.html/ public String findAllUser(){ System.out.println("---------------"); List<User> list= userService.findAllUsers(); System.out.println("---------------"+list); log.info(list); getRequest().setAttribute("userList", list); return "findall"; } public String toAddUser(){ return "toadd"; } public String addUser(){ User auser= userService.addUser(user); log.info(" after add :" + auser); if (null == user) return "adduser-error"; return "adduser-success"; } public String deleteUser(){ userService.deleteUser(new User(id)); return "deleteuser"; } public String toEdit(){ User auser = userService.getUserById(new User(id)); log.info(" to edit :" + auser); getRequest().setAttribute("user", auser); return "toedit"; } public String editUser(){ int i = userService.updateUser(user); log.info(" after edit :" + (i>=1?true: false)); if (i>=1) { getRequest().setAttribute("id", user.getUserId()); return "updateuser-error"; } return "updateuser-success"; } // get set public User getUser() { return user; } public void setUser(User user) { this.user = user; } public int getId() { return id; } public void setId(int id) { this.id = id; } }
User
package com.baoy.cn.bean; import static javax.persistence.GenerationType.IDENTITY; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; /** * @author baoyou E-mail:[email protected] * @version 创建时间:2015年12月5日 下午9:54:16 des: */ @Entity @Table(name = "t_user") public class User implements Serializable { public User() { } public User(int userId) { this.userId =userId; } @Override public String toString() { return "User [userId=" + userId + ", userName=" + userName + ", password=" + password + ", tel=" + tel + ", sex=" + sex + ", description=" + description + "]"; } @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "userId", unique = true, nullable = false) private int userId; @Column(name = "userName") private String userName; @Column(name = "password") private String password; @Column(name = "tel") private String tel; @Column(name = "sex") private String sex; @Column(name = "description") private String description; public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getTel() { return tel; } public void setTel(String tel) { this.tel = tel; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
UserService
package com.baoy.cn.service; import java.util.List; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; import com.baoy.cn.bean.User; import com.baoy.cn.core.BaseService; /** * @author baoyou E-mail:[email protected] * @version 创建时间:2015年12月5日 下午10:21:09 * des: */ @Scope("singleton") @Service("userService") public interface UserService extends BaseService<User>{ public List<User> findAllUsers(); public User getUserById(User user); public User getUserByName(User user); public User addUser(User user); public int deleteUser(User user); public int updateUser(User user); }
UserServiceImpl
package com.baoy.cn.serviceimpl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; import com.baoy.cn.bean.User; import com.baoy.cn.core.BaseServiceImpl; import com.baoy.cn.dao.UserDao; import com.baoy.cn.service.UserService; /** * @author baoyou E-mail:[email protected] * @version 创建时间:2015年12月5日 下午10:21:49 * des: */ @Scope("singleton") @Service("userServiceImpl") public class UserServiceImpl extends BaseServiceImpl<User> implements UserService { @Autowired public void setDao(UserDao dao) { super.setDao(dao); } public UserDao getDao() { return (UserDao) super.getDao(); } @Override public List<User> findAllUsers() { //自己实现 //return this.getDao().findAllUsers(); //框架实现 return this.getDao().findAll(); } @Override public User getUserById(User user) { //自己实现 //return this.getDao().getUserById(user); //框架实现 return this.getDao().findUniqueByProperty("userId", user.getUserId()); } @Override public User getUserByName(User user) { //自己实现 //return this.getDao().getUserByName(user); //框架实现 return this.getDao().findUniqueByProperty("userName", user.getUserName()); } @Override public User addUser(User user) { //自己实现 //return this.getDao().addUser(user); //框架实现 return this.getDao().save(user); } @Override public int deleteUser(User user) { //自己实现 //return this.getDao().deleteUser(user); //框架实现 User auser =this.getDao().deleteById( (user.getUserId())); return 1; } @Override public int updateUser(User user) { //自己实现 //return this.getDao().updateUser(user); //框架实现 User auser= (User) this.getDao().update(user); return 1; } }
UserDao
package com.baoy.cn.dao; import java.util.List; import com.baoy.cn.bean.User; import com.baoy.cn.core.BaseDao; /** * @author baoyou E-mail:[email protected] * @version 创建时间:2015年12月5日 下午10:05:19 des: */ public interface UserDao extends BaseDao<User> { public List<User> findAllUsers(); public User getUserById(User user); public User getUserByName(User user); public User addUser(User user); public int deleteUser(User user); public int updateUser(User user); }
UserDaoImpl
package com.baoy.cn.daoimpl; import java.util.List; import org.hibernate.Query; import org.springframework.stereotype.Repository; import com.baoy.cn.bean.User; import com.baoy.cn.core.BaseDaoImpl; import com.baoy.cn.dao.UserDao; /** * @author baoyou E-mail:[email protected] * @version 创建时间:2015年12月5日 下午10:09:01 * des: */ @Repository public class UserDaoImpl extends BaseDaoImpl<User> implements UserDao{ @SuppressWarnings("unchecked") @Override public List<User> findAllUsers() { Query query = this.getSession().createQuery("from User"); return query.list(); } @Override public User getUserById(User user) { Query query = this.getSession().createSQLQuery("select * from t_user where userId=:userId").addEntity(User.class); query.setParameter("userId", user.getUserId()); return (User)query.uniqueResult(); } @Override public User getUserByName(User user) { Query query = this.getSession().createSQLQuery("select * from t_user where userName=:userName").addEntity(User.class); query.setParameter("userName", user.getUserName()); return (User)query.uniqueResult(); } @Override public User addUser(User user) { return this.save(user); } @Override public int deleteUser(User user) { String sql = "delete from t_user where userId ="+user.getUserId(); Query query = this.getSession().createSQLQuery(sql); int rs = query.executeUpdate(); return rs; } @Override public int updateUser(User user) { String sql = "update t_user set userName='"+user.getUserName()+"',password='"+user.getPassword()+"',tel='"+user.getTel()+"',sex='"+user.getSex()+"',description='"+user.getDescription()+"' where userId ="+user.getUserId(); Query query = this.getSession().createSQLQuery(sql); int rs = query.executeUpdate(); return rs; } }
AuthInterceptor
package com.baoy.cn.core; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.AbstractInterceptor; public class AuthInterceptor extends AbstractInterceptor { private static final long serialVersionUID = 8514282210475728866L; @Override public String intercept(ActionInvocation invocation) throws Exception { return invocation.invoke(); } }
BaseAction
package com.baoy.cn.core; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; /** * base action * @author baoy * */ public class BaseAction extends ActionSupport{ private static final long serialVersionUID = 5963166559711175502L; public HttpServletRequest getRequest() { return ServletActionContext.getRequest(); } public HttpServletResponse getResponse() { return ServletActionContext.getResponse(); } public ServletContext getContext() { return ServletActionContext.getServletContext(); } public HttpSession getSession() { return getRequest().getSession(); } }
BaseDao
package com.baoy.cn.core; import java.io.Serializable; import java.util.Collection; import java.util.List; /** * 功能说明 :提供底层数据库操作功能的DAO基类 * creation date: 04-09-2013 */ public interface BaseDao<T extends Serializable> { /** * 通过ID查找对象 * @param id 记录的ID * @param lock 是否锁定对象 * @return 实体对象 */ public T load(Serializable id, boolean lock); /** * 通过ID查找对象 * @param id 记录的ID * @return 实体对象 */ public T get(Serializable id); /** * 通过ID查找对象 * @param id 记录的ID * @return 实体对象 */ public T load(Serializable id); /** * 查找所有对象 * @return 对象列表 */ public List<T> findAll(); /** * 查找所有对象 * @param orders 查询的排序对象集 * @return 对象列表 */ public List<T> findAll(OrderBy... orders); /** * 按属性查找对象列表. * @param property 属性名 * @param value 属性值 */ public List<T> findByProperty(String property, Object value); /** * 按属性查找唯一对象. * @param property 属性名 * @param value 属性值 */ public T findUniqueByProperty(String property, Object value); /** * 按属性查找对象的数量 * @param property 属性名 * @param value 属性值 * @return int 对象的数量 */ public int countByProperty(String property, Object value); /** * 保存对象 * @param entity 实体对象 * @return T 实体对象 */ public T save(T entity); /** * 更新对象 * @param entity 实体对象 * @return Object 实体对象 */ public Object update(Object entity); /** * 保存集合中所有对象 * @param colle 实体集合 * @return void */ public void saveAll(Collection<?> colle); /** * 修改集合中所有对象 * @param colle 实体集合 * @return void */ public void updateAll(Collection<?> colle); /** * 保存或更新对象 * @param entity 实体对象 * @return 实体对象 */ public Object saveOrUpdate(Object entity); /** * 保存或更新集合中的所有对象 * @param colle 实体对象集合 * @return void */ public void saveOrUpdateAll(Collection<?> colle); /** * 保存或更新对象拷贝 * @param entity 待合并的实例 * @return Object 已更新的持久化对象 */ public Object merge(Object entity); /** * 删除对象 * @param entity 实体对象 * @return void */ public void delete(Object entity); /** * 删除集合中所有对象 * @param colle 实体对象列表 * @return void */ public void deleteAll(Collection<?> colle); /** * 根据ID删除记录 * @param id 记录ID * @return T 删除的对象 */ public T deleteById(Serializable id); /** * 刷新对象 * @param entity 实例对象 */ public void refresh(Object entity); /** * 获得实体Class * @return Class */ public Class<T> getPersistentClass(); /** * 创建实体类的对象 * @return T 泛型实例 */ public T createNewEntiey(); }
BaseDaoImpl
package com.baoy.cn.core; import java.io.Serializable; import java.lang.reflect.ParameterizedType; import java.sql.Connection; import java.util.Collection; import java.util.Iterator; import java.util.List; import org.apache.log4j.Logger; import org.hibernate.Criteria; import org.hibernate.LockOptions; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.criterion.Criterion; import org.hibernate.criterion.Projections; import org.hibernate.criterion.Restrictions; import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider; import org.hibernate.engine.spi.SessionFactoryImplementor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.util.Assert; /** * 功能说明 :提供底层数据库操作功能的DAO基类 * creation date: 04-09-2013 */ @Repository public abstract class BaseDaoImpl<T extends Serializable> implements BaseDao<T> { protected Logger log = Logger.getLogger(getClass()); public Connection jdbcConn = null; public ConnectionProvider cp = null; protected SessionFactory sessionFactory; @Autowired public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } protected Session getSession() { return sessionFactory.getCurrentSession(); } @SuppressWarnings("deprecation") public Connection getJdbcConnection() throws Exception{ try { cp = ((SessionFactoryImplementor)this.sessionFactory).getConnectionProvider(); jdbcConn = cp.getConnection(); } catch (Exception e) { throw e; } return jdbcConn; } @SuppressWarnings("deprecation") public void closeJdbcConnection(Connection conn) throws Exception{ try { if(null!=conn){ if(null!=cp) cp = ((SessionFactoryImplementor)this.sessionFactory).getConnectionProvider(); cp.closeConnection(conn); } } catch (Exception e) { throw e; } } /** * 保存对象 * @param entity 实体对象 * @return T 实体对象 */ public T save(T entity) { Assert.notNull(entity); getSession().save(entity); return entity; } /** * 更新对象 * @param entity 实体对象 * @return Object 实体对象 */ public Object update(Object entity) { Assert.notNull(entity); getSession().update(entity); return entity; } /** * 修改集合中所有对象 * @param colle 实体集合 * @return void */ public void updateAll(Collection<?> colle) { if (colle != null) { Iterator<?> it = colle.iterator(); while (it.hasNext()) { update(it.next()); } } } /** * 保存或更新对象 * @param entity 实体对象 * @return 实体对象 */ public Object saveOrUpdate(Object entity) { Assert.notNull(entity); getSession().saveOrUpdate(entity); return entity; } /** * 保存或更新集合中的所有对象 * @param colle 实体对象集合 * @return void */ public void saveOrUpdateAll(Collection<?> colle) { if (colle != null) { Iterator<?> it = colle.iterator(); while (it.hasNext()) { saveOrUpdate(it.next()); } } } /** * 保存集合中所有对象 * @param colle 实体集合 * @return void */ public void saveAll(Collection<?> colle) { if (colle != null) { Iterator<?> it = colle.iterator(); while (it.hasNext()) { getSession().save(it.next()); } } } /** * 保存或更新对象拷贝 * @param entity 待合并的实例 * @return Object 已更新的持久化对象 */ public Object merge(Object entity) { Assert.notNull(entity); return getSession().merge(entity); } /** * 删除对象 * @param entity 实体对象 * @return void */ public void delete(Object entity) { Assert.notNull(entity); getSession().delete(entity); } /** * 删除集合中所有对象 * @param colle 实体对象列表 * @return void */ public void deleteAll(Collection<?> colle) { if (colle != null) { Iterator<?> it = colle.iterator(); while (it.hasNext()) { delete(it.next()); } } } /** * 根据ID删除记录 * @param id 记录ID * @return T 删除的对象 */ public T deleteById(Serializable id) { Assert.notNull(id); T entity = load(id); getSession().delete(entity); return entity; } /** * 通过ID查找对象 * @param id 记录的ID * @return 实体对象 */ public T load(Serializable id) { Assert.notNull(id); return load(id, false); } /** * 通过ID查找对象 * @param id 记录的ID * @return 实体对象 */ @SuppressWarnings("unchecked") public T get(Serializable id) { Assert.notNull(id); return (T) getSession().get(getPersistentClass(), id); } /** * 通过ID查找对象 * @param id 记录的ID * @param lock 是否锁定对象 * @return 实体对象 */ @SuppressWarnings("unchecked") public T load(Serializable id, boolean lock) { Assert.notNull(id); T entity = null; if (lock) { entity = (T) getSession().load(getPersistentClass(), id, LockOptions.UPGRADE); } else { entity = (T) getSession().load(getPersistentClass(), id); } return entity; } /** * 查找所有对象 * @return 对象列表 */ public List<T> findAll() { return findByCriteria(); } /** * 查找所有对象 * @param orders 查询的排序对象集 * @return 对象列表 */ @SuppressWarnings("unchecked") public List<T> findAll(OrderBy... orders) { Criteria crit = createCriteria(); if (orders != null) { for (OrderBy order : orders) { crit.addOrder(order.getOrder()); } } return crit.list(); } /** * 按HQL查询对象列表. * @param hql hql语句 * @param values 数量可变的参数 */ protected List<?> find(String hql, Object... values) { return createQuery(hql, values).list(); } /** * 按HQL查询唯一对象. * @param hql HQL查询语句 * @param value 参数对应的值列表 * @return Object 泛型实例 */ protected Object findUnique(String hql, Object... values) { return createQuery(hql, values).uniqueResult(); } /** * 按属性查找对象列表. * @param property 对象属性 * @param value 对象属性值 * @return List<T> 泛型实例列表 */ @SuppressWarnings("unchecked") public List<T> findByProperty(String property, Object value) { Assert.hasText(property); return createCriteria(Restrictions.eq(property, value)).list(); } /** * 按属性模糊查找对象列表 * @param property 对象属性 * @param value 对象属性值 * @return List<T> 泛型实例列表 */ @SuppressWarnings("unchecked") public List<T> findByNotNllProperty(String property,Object value) { Assert.hasText(property); return createCriteria(Restrictions.like(property, value)).list(); } /** * 按属性查找对象列表,属性必须为NOT NULL * @param property 对象属性 * @param value 对象属性值 * @return List<T> 泛型实例列表 */ @SuppressWarnings("unchecked") public List<T> findByNotNllProperty(String property) { Assert.hasText(property); return createCriteria(Restrictions.isNotNull(property)).list(); } /** * 按属性查找对象列表,属性必须为NULL * @param property 对象属性 * @param value 对象属性值 * @return List<T> 泛型实例列表 */ @SuppressWarnings("unchecked") public List<T> findByNllProperty(String property) { Assert.hasText(property); return createCriteria(Restrictions.isNull(property)).list(); } /** * 按属性查找对象列表,属性必须为空字符串 * @param property 对象属性 * @param value 对象属性值 * @return List<T> 泛型实例列表 */ @SuppressWarnings("unchecked") public List<T> findByEmptyProperty(String property) { Assert.hasText(property); return createCriteria(Restrictions.isEmpty(property)).list(); } /** * 按属性查找对象列表,属性必须为非空字符串 * @param property 对象属性 * @param value 对象属性值 * @return List<T> 泛型实例列表 */ @SuppressWarnings("unchecked") public List<T> findByNotEmptyProperty(String property) { Assert.hasText(property); return createCriteria(Restrictions.isNotEmpty(property)).list(); } /** * 按属性查找唯一对象 * @param property 对象属性 * @param value 对象属性值 */ @SuppressWarnings("unchecked") public T findUniqueByProperty(String property, Object value) { Assert.hasText(property); Assert.notNull(value); return (T) createCriteria(Restrictions.eq(property, value)).uniqueResult(); } /** * 按属性统计对象数量 * @param property 对象属性 * @param value 对象属性值 */ public int countByProperty(String property, Object value) { Assert.hasText(property); Assert.notNull(value); return ((Number) (createCriteria(Restrictions.eq(property, value)).setProjection(Projections.rowCount()) .uniqueResult())).intValue(); } /** * 根据查询函数与参数列表创建Query对象,后续可进行更多处理,辅助函数. */ protected 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; } /** * 按Criterion查询对象列表. * @param criterion 数量可变的Criterion. */ @SuppressWarnings("unchecked") protected List<T> findByCriteria(Criterion... criterion) { return createCriteria(criterion).list(); } /** * 刷新对象 * @param entity 实例对象 */ public void refresh(Object entity) { getSession().refresh(entity); } /** * 根据criterions条件创建Criteria,后续可进行更多处理,辅助函数. */ protected Criteria createCriteria(Criterion... criterions) { Criteria criteria = getSession().createCriteria(getPersistentClass()); for (Criterion c : criterions) { criteria.add(c); } return criteria; } private Class<T> persistentClass; @SuppressWarnings("unchecked") public BaseDaoImpl() { this.persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()) .getActualTypeArguments()[0]; } /** * 获得实体Class * @return Class */ public Class<T> getPersistentClass() { return persistentClass; } /** * 创建实体类的对象 * @return T 泛型实例 */ public T createNewEntiey() { try { return getPersistentClass().newInstance(); } catch (Exception e) { throw new RuntimeException("不能创建实体对象:" + getPersistentClass().getName()); } } }
BaseService
package com.baoy.cn.core; import java.io.Serializable; import java.util.Collection; import java.util.List; /** * 功能说明 :提供底层数据库操作功能 * * @author * creation date: 04-09-2013 */ public interface BaseService<T extends Serializable> { public boolean isServiceReady(); /** * 通过ID查找对象 * * @param id * 记录的ID * @return 实体对象 */ public T findById(Serializable id); /** * 通过ID查找对象 * * @param id * 记录的ID * @param lock * 是否锁定对象 * @return 实体对象 */ public T load(Serializable id); /** * 查找所有对象 * * @return 对象列表 */ public List<T> findAll(); /** * 保存集合中所有对象 * * @param colle * 实体集合 * @return void */ public T save(T entity); /** * 更新对象 * * @param entity * 实体对象 * @return Object 实体对象 */ public Object update(Object o); /** * 保存或更新对象 * * @param entity * 实体对象 * @return 实体对象 */ public Object saveOrUpdate(Object o); /** * 删除对象 * * @param entity * 实体对象 * @return void */ public void delete(Object o); /** * 删除集合中所有对象 * * @param colle * 实体对象列表 * @return void */ public void deleteAll(Collection<?> colle); /** * 根据ID删除记录 * * @param id * 记录ID * @return T 删除的对象 */ public T deleteById(Serializable id); /** * 根据ID数组删除记录 * * @param ids * 记录ID数组 * @return T 删除的对象列表 */ public List<T> deleteById(Serializable[] ids); /** * 刷新对象 * * @param entity * 实例对象 */ public T saveAndRefresh(T entity); }
BaseServiceImpl
package com.baoy.cn.core; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.apache.log4j.Logger; import org.springframework.transaction.annotation.Transactional; /** * 功能说明 :提供底层数据库操作功能 * * @author * creation date: 04-09-2013 */ @Transactional public class BaseServiceImpl<T extends Serializable> implements BaseService<T> { protected Logger log = Logger.getLogger(getClass()); private BaseDao<T> dao; public void setDao(BaseDao<T> dao) { this.dao = dao; } protected BaseDao<T> getDao() { return this.dao; } public boolean isServiceReady() { return getDao() != null; } /** * 通过ID查找对象 * * @param id * 记录的ID * @return 实体对象 */ @Transactional(readOnly = true) public T findById(Serializable id) { try { return dao.get(id); } catch (Exception e) { return null; } } /** * 通过ID查找对象 * * @param id * 记录的ID * @param lock * 是否锁定对象 * @return 实体对象 */ @Transactional(readOnly = true) public T load(Serializable id) { try { return dao.load(id); } catch (Exception e) { return null; } } /** * 查找所有对象 * * @return 对象列表 */ @Transactional(readOnly = true) public List<T> findAll() { return dao.findAll(); } /** * 保存对象 * * @param entity * 实体对象 * @return T 实体对象 */ public T save(T entity) { return dao.save(entity); } /** * 刷新对象 * * @param entity * 实例对象 */ public T saveAndRefresh(T entity) { this.save(entity); getDao().refresh(entity); return entity; } /** * 保存或更新对象 * * @param entity * 实体对象 * @return 实体对象 */ public Object saveOrUpdate(Object o) { return getDao().saveOrUpdate(o); } /** * 删除对象 * * @param entity * 实体对象 * @return void */ public void delete(Object o) { getDao().delete(o); } /** * 删除集合中所有对象 * * @param colle * 实体对象列表 * @return void */ public void deleteAll(Collection<?> colle) { getDao().deleteAll(colle); } /** * 更新对象 * * @param entity * 实体对象 * @return Object 实体对象 */ public Object update(Object o) { return getDao().update(o); } /** * 保存或更新对象拷贝 * * @param entity * 待合并的实例 * @return Object 已更新的持久化对象 */ public Object merge(Object o) { return getDao().merge(o); } /** * 根据ID删除记录 * * @param id * 记录ID * @return T 删除的对象 */ public T deleteById(Serializable id) { if (id == null) { return null; } return dao.deleteById(id); } /** * 根据ID数组删除记录 * * @param ids * 记录ID数组 * @return T 删除的对象列表 */ public List<T> deleteById(Serializable[] ids) { List<T> dts = new ArrayList<T>(); T del = null; if (ids != null && ids.length > 0) { for (Serializable id : ids) { del = deleteById(id); if (del != null) { dts.add(del); } } } return dts; } }
OrderBy
package com.baoy.cn.core; import java.io.Serializable; import org.hibernate.criterion.Order; public class OrderBy implements Serializable { private static final long serialVersionUID = -2898312981178692072L; private OrderType orderType; protected String field; protected OrderBy(String field, OrderType orderType) { this.field = field; this.orderType = orderType; } public static OrderBy asc(String field) { return new OrderBy(field, OrderType.ASC); } public static OrderBy desc(String field) { return new OrderBy(field, OrderType.DESC); } public String getField() { return field; } public Order getOrder() { Order order = null; if (OrderType.ASC == orderType) { order = Order.asc(getField()); } else if (OrderType.DESC == orderType) { order = Order.desc(getField()); } return order; } public static Order[] asOrders(OrderBy[] orderBys) { if (orderBys != null) { Order[] orders = new Order[orderBys.length]; for (int i = 0; i < orderBys.length; i++) { orders[i] = orderBys[i].getOrder(); } return orders; } else { return null; } } public static enum OrderType { ASC, DESC } }
ehcache.xml
<?xml version="1.0" encoding="UTF-8"?> <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="false" monitoring="autodetect" dynamicConfig="true" name="example"> <diskStore path="java.io.tmpdir" /> <defaultCache maxElementsInMemory="1000" eternal="false" timeToIdleSeconds="60" timeToLiveSeconds="120" overflowToDisk="true" /> </ehcache>
ehcache.xsd
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" version="1.7"> <xs:element name="ehcache"> <xs:complexType> <xs:sequence> <xs:element maxOccurs="1" minOccurs="0" ref="diskStore"/> <xs:element maxOccurs="1" minOccurs="0" ref="sizeOfPolicy"/> <xs:element maxOccurs="1" minOccurs="0" ref="transactionManagerLookup"/> <xs:element maxOccurs="1" minOccurs="0" ref="cacheManagerEventListenerFactory"/> <xs:element maxOccurs="1" minOccurs="0" ref="managementRESTService"/> <xs:element maxOccurs="unbounded" minOccurs="0" ref="cacheManagerPeerProviderFactory"/> <xs:element maxOccurs="unbounded" minOccurs="0" ref="cacheManagerPeerListenerFactory"/> <xs:element maxOccurs="1" minOccurs="0" ref="terracottaConfig"/> <xs:element maxOccurs= "1" minOccurs="0" ref="defaultCache"/> <xs:element maxOccurs="unbounded" minOccurs="0" ref="cache"/> </xs:sequence> <xs:attribute name="name" use="optional"/> <xs:attribute default="true" name="updateCheck" type="xs:boolean" use="optional"/> <xs:attribute default="autodetect" name="monitoring" type="monitoringType" use="optional"/> <xs:attribute default="true" name="dynamicConfig" type="xs:boolean" use="optional"/> <xs:attribute default="15" name="defaultTransactionTimeoutInSeconds" type="xs:integer" use="optional"/> <xs:attribute default="0" name="maxBytesLocalHeap" type="memoryUnitOrPercentage" use="optional"/> <xs:attribute default="0" name="maxBytesLocalOffHeap" type="memoryUnit" use="optional"/> <xs:attribute default="0" name="maxBytesLocalDisk" type="memoryUnit" use="optional"/> </xs:complexType> </xs:element> <xs:element name="managementRESTService"> <xs:complexType> <xs:attribute name="enabled" type="xs:boolean" use="optional"/> <xs:attribute name="bind" use="optional"/> <xs:attribute name="securityServiceLocation" use="optional"/> <xs:attribute name="securityServiceTimeout" use="optional" type="xs:integer"/> <xs:attribute name="sslEnabled" use="optional" type="xs:boolean"/> <xs:attribute name="needClientAuth" use="optional" type="xs:boolean"/> <xs:attribute name="sampleHistorySize" use="optional" type="xs:integer"/> <xs:attribute name="sampleIntervalSeconds" use="optional" type="xs:integer"/> <xs:attribute name="sampleSearchIntervalSeconds" use="optional" type="xs:integer"/> </xs:complexType> </xs:element> <xs:element name="diskStore"> <xs:complexType> <xs:attribute name="path" use="optional"/> </xs:complexType> </xs:element> <xs:element name="transactionManagerLookup"> <xs:complexType> <xs:attribute name="class" use="required"/> <xs:attribute name="properties" use="optional"/> <xs:attribute name="propertySeparator" use="optional"/> </xs:complexType> </xs:element> <xs:element name="cacheManagerEventListenerFactory"> <xs:complexType> <xs:attribute name="class" use="required"/> <xs:attribute name="properties" use="optional"/> <xs:attribute name="propertySeparator" use="optional"/> </xs:complexType> </xs:element> <xs:element name="cacheManagerPeerProviderFactory"> <xs:complexType> <xs:attribute name="class" use="required"/> <xs:attribute name="properties" use="optional"/> <xs:attribute name="propertySeparator" use="optional"/> </xs:complexType> </xs:element> <xs:element name="cacheManagerPeerListenerFactory"> <xs:complexType> <xs:attribute name="class" use="required"/> <xs:attribute name="properties" use="optional"/> <xs:attribute name="propertySeparator" use="optional"/> </xs:complexType> </xs:element> <xs:element name="terracottaConfig"> <xs:complexType> <xs:sequence> <xs:element maxOccurs="1" minOccurs="0" name="tc-config"> <xs:complexType> <xs:sequence> <xs:any maxOccurs="unbounded" minOccurs="0" processContents="skip"/> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> <xs:attribute default="localhost:9510" name="url" use="optional"/> <xs:attribute name="rejoin" type="xs:boolean" use="optional" default="false"/> <xs:attribute name="wanEnabledTSA" type="xs:boolean" use="optional" default="false"/> </xs:complexType> </xs:element> <!-- add clone support for addition of cacheExceptionHandler. Important! --> <xs:element name="defaultCache"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" maxOccurs="unbounded" ref="cacheEventListenerFactory"/> <xs:element minOccurs="0" maxOccurs="unbounded" ref="cacheExtensionFactory"/> <xs:element minOccurs="0" maxOccurs="unbounded" ref="cacheLoaderFactory"/> <xs:element minOccurs="0" maxOccurs="unbounded" ref="cacheDecoratorFactory"/> <xs:element minOccurs="0" maxOccurs="1" ref="bootstrapCacheLoaderFactory"/> <xs:element minOccurs="0" maxOccurs="1" ref="cacheExceptionHandlerFactory"/> <xs:element minOccurs="0" maxOccurs="1" ref="pinning"/> <xs:element minOccurs="0" maxOccurs="1" ref="terracotta"/> <xs:element minOccurs="0" maxOccurs="1" ref="cacheWriter"/> <xs:element minOccurs="0" maxOccurs="1" ref="copyStrategy"/> <xs:element minOccurs="0" maxOccurs="1" ref="elementValueComparator"/> <xs:element minOccurs="0" maxOccurs="1" ref="sizeOfPolicy"/> <xs:element minOccurs="0" maxOccurs="1" ref="persistence"/> </xs:sequence> <xs:attribute name="diskExpiryThreadIntervalSeconds" type="xs:integer" use="optional"/> <xs:attribute name="diskSpoolBufferSizeMB" type="xs:integer" use="optional"/> <xs:attribute name="diskPersistent" type="xs:boolean" use="optional"/> <xs:attribute name="diskAccessStripes" type="xs:integer" use="optional" default="1"/> <xs:attribute name="eternal" type="xs:boolean" use="optional" default="false"/> <xs:attribute name="maxElementsInMemory" type="xs:nonNegativeInteger" use="optional"/> <xs:attribute name="maxEntriesLocalHeap" type="xs:nonNegativeInteger" use="optional"/> <xs:attribute name="clearOnFlush" type="xs:boolean" use="optional"/> <xs:attribute name="memoryStoreEvictionPolicy" type="xs:string" use="optional"/> <xs:attribute name="overflowToDisk" type="xs:boolean" use="optional"/> <xs:attribute name="timeToIdleSeconds" type="xs:nonNegativeInteger" use="optional"/> <xs:attribute name="timeToLiveSeconds" type="xs:nonNegativeInteger" use="optional"/> <xs:attribute name="maxElementsOnDisk" type="xs:nonNegativeInteger" use="optional"/> <xs:attribute name="maxEntriesLocalDisk" type="xs:nonNegativeInteger" use="optional"/> <xs:attribute name="transactionalMode" type="transactionalMode" use="optional" default="off"/> <xs:attribute name="statistics" type="xs:boolean" use="optional" default="false"/> <xs:attribute name="copyOnRead" type="xs:boolean" use="optional" default="false"/> <xs:attribute name="copyOnWrite" type="xs:boolean" use="optional" default="false"/> <xs:attribute name="cacheLoaderTimeoutMillis" type="xs:integer" use="optional" default="0"/> <xs:attribute name="overflowToOffHeap" type="xs:boolean" use="optional" default="false"/> <xs:attribute name="maxMemoryOffHeap" type="xs:string" use="optional"/> </xs:complexType> </xs:element> <xs:element name="cache"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" maxOccurs="unbounded" ref="cacheEventListenerFactory"/> <xs:element minOccurs="0" maxOccurs="unbounded" ref="cacheExtensionFactory"/> <xs:element minOccurs="0" maxOccurs="unbounded" ref="cacheLoaderFactory"/> <xs:element minOccurs="0" maxOccurs="unbounded" ref="cacheDecoratorFactory"/> <xs:element minOccurs="0" maxOccurs="1" ref="bootstrapCacheLoaderFactory"/> <xs:element minOccurs="0" maxOccurs="1" ref="cacheExceptionHandlerFactory"/> <xs:element minOccurs="0" maxOccurs="1" ref="pinning"/> <xs:element minOccurs="0" maxOccurs="1" ref="terracotta"/> <xs:element minOccurs="0" maxOccurs="1" ref="cacheWriter"/> <xs:element minOccurs="0" maxOccurs="1" ref="copyStrategy"/> <xs:element minOccurs="0" maxOccurs="1" ref="searchable"/> <xs:element minOccurs="0" maxOccurs="1" ref="elementValueComparator"/> <xs:element minOccurs="0" maxOccurs="1" ref="sizeOfPolicy"/> <xs:element minOccurs="0" maxOccurs="1" ref="persistence"/> </xs:sequence> <xs:attribute name="diskExpiryThreadIntervalSeconds" type="xs:integer" use="optional"/> <xs:attribute name="diskSpoolBufferSizeMB" type="xs:integer" use="optional"/> <xs:attribute name="diskPersistent" type="xs:boolean" use="optional"/> <xs:attribute name="diskAccessStripes" type="xs:integer" use="optional" default="1"/> <xs:attribute name="eternal" type="xs:boolean" use="optional" default="false"/> <xs:attribute name="maxElementsInMemory" type="xs:nonNegativeInteger" use="optional"/> <xs:attribute name="maxEntriesLocalHeap" type="xs:nonNegativeInteger" use="optional"/> <xs:attribute name="memoryStoreEvictionPolicy" type="xs:string" use="optional"/> <xs:attribute name="clearOnFlush" type="xs:boolean" use="optional"/> <xs:attribute name="name" type="xs:string" use="required"/> <xs:attribute name="overflowToDisk" type="xs:boolean" use="optional"/> <xs:attribute name="timeToIdleSeconds" type="xs:nonNegativeInteger" use="optional"/> <xs:attribute name="timeToLiveSeconds" type="xs:nonNegativeInteger" use="optional"/> <xs:attribute name="maxElementsOnDisk" type="xs:nonNegativeInteger" use="optional"/> <xs:attribute name="maxEntriesLocalDisk" type="xs:nonNegativeInteger" use="optional"/> <xs:attribute name="maxEntriesInCache" type="xs:nonNegativeInteger" use="optional"/> <xs:attribute name="transactionalMode" type="transactionalMode" use="optional" default="off" /> <xs:attribute name="statistics" type="xs:boolean" use="optional" default="false"/> <xs:attribute name="copyOnRead" type="xs:boolean" use="optional" default="false"/> <xs:attribute name="copyOnWrite" type="xs:boolean" use="optional" default="false"/> <xs:attribute name="logging" type="xs:boolean" use="optional" default="false"/> <xs:attribute name="cacheLoaderTimeoutMillis" type="xs:integer" use="optional" default="0"/> <xs:attribute name="overflowToOffHeap" type="xs:boolean" use="optional" default="false"/> <xs:attribute name="maxMemoryOffHeap" type="xs:string" use="optional"/> <xs:attribute default="0" name="maxBytesLocalHeap" type="memoryUnitOrPercentage" use="optional"/> <xs:attribute default="0" name="maxBytesLocalOffHeap" type="memoryUnitOrPercentage" use="optional"/> <xs:attribute default="0" name="maxBytesLocalDisk" type="memoryUnitOrPercentage" use="optional"/> </xs:complexType> </xs:element> <xs:element name="cacheEventListenerFactory"> <xs:complexType> <xs:attribute name="class" use="required"/> <xs:attribute name="properties" use="optional"/> <xs:attribute name="propertySeparator" use="optional"/> <xs:attribute name="listenFor" use="optional" type="notificationScope" default="all"/> </xs:complexType> </xs:element> <xs:element name="bootstrapCacheLoaderFactory"> <xs:complexType> <xs:attribute name="class" use="required"/> <xs:attribute name="properties" use="optional"/> <xs:attribute name="propertySeparator" use="optional"/> </xs:complexType> </xs:element> <xs:element name="cacheExtensionFactory"> <xs:complexType> <xs:attribute name="class" use="required"/> <xs:attribute name="properties" use="optional"/> <xs:attribute name="propertySeparator" use="optional"/> </xs:complexType> </xs:element> <xs:element name="cacheExceptionHandlerFactory"> <xs:complexType> <xs:attribute name="class" use="required"/> <xs:attribute name="properties" use="optional"/> <xs:attribute name="propertySeparator" use="optional"/> </xs:complexType> </xs:element> <xs:element name="cacheLoaderFactory"> <xs:complexType> <xs:attribute name="class" use="required"/> <xs:attribute name="properties" use="optional"/> <xs:attribute name="propertySeparator" use="optional"/> </xs:complexType> </xs:element> <xs:element name="cacheDecoratorFactory"> <xs:complexType> <xs:attribute name="class" use="required"/> <xs:attribute name="properties" use="optional"/> <xs:attribute name="propertySeparator" use="optional"/> </xs:complexType> </xs:element> <xs:element name="searchAttribute"> <xs:complexType> <xs:attribute name="name" use="required" type="xs:string" /> <xs:attribute name="expression" type="xs:string" /> <xs:attribute name="class" type="xs:string" /> <xs:attribute name="type" type="xs:string" use="optional"/> <xs:attribute name="properties" use="optional" /> <xs:attribute name="propertySeparator" use="optional" /> </xs:complexType> </xs:element> <xs:element name="searchable"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" maxOccurs="unbounded" ref="searchAttribute"/> </xs:sequence> <xs:attribute name="keys" use="optional" type="xs:boolean" default="true"/> <xs:attribute name="values" use="optional" type="xs:boolean" default="true"/> </xs:complexType> </xs:element> <xs:element name="pinning"> <xs:complexType> <xs:attribute name="store" use="required" type="pinningStoreType"/> </xs:complexType> </xs:element> <xs:element name="terracotta"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" maxOccurs="1" ref="nonstop"/> </xs:sequence> <xs:attribute name="clustered" use="optional" type="xs:boolean" default="true"/> <xs:attribute name="coherentReads" use="optional" type="xs:boolean" default="true"/> <xs:attribute name="localKeyCache" use="optional" type="xs:boolean" default="false"/> <xs:attribute name="localKeyCacheSize" use="optional" type="xs:positiveInteger" default="300000"/> <xs:attribute name="orphanEviction" use="optional" type="xs:boolean" default="true"/> <xs:attribute name="orphanEvictionPeriod" use="optional" type="xs:positiveInteger" default="4"/> <xs:attribute name="copyOnRead" use="optional" type="xs:boolean" default="false"/> <xs:attribute name="coherent" use="optional" type="xs:boolean" default="false"/> <xs:attribute name="consistency" use="optional" type="consistencyType" default="eventual"/> <xs:attribute name="synchronousWrites" use="optional" type="xs:boolean" default="false"/> <xs:attribute name="concurrency" use="optional" type="xs:nonNegativeInteger" default="0"/> <xs:attribute name="localCacheEnabled" use="optional" type="xs:boolean" default="true"/> <xs:attribute name="compressionEnabled" use="optional" type="xs:boolean" default="false"/> </xs:complexType> </xs:element> <xs:simpleType name="consistencyType"> <xs:restriction base="xs:string"> <xs:enumeration value="strong" /> <xs:enumeration value="eventual" /> </xs:restriction> </xs:simpleType> <xs:element name="nonstop"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" maxOccurs="1" ref="timeoutBehavior"/> </xs:sequence> <xs:attribute name="enabled" use="optional" type="xs:boolean" default="true"/> <xs:attribute name="immediateTimeout" use="optional" type="xs:boolean" default="false"/> <xs:attribute name="timeoutMillis" use="optional" type="xs:positiveInteger" default="30000"/> <xs:attribute name="searchTimeoutMillis" use="optional" type="xs:positiveInteger" default="30000"/> </xs:complexType> </xs:element> <xs:element name="timeoutBehavior"> <xs:complexType> <xs:attribute name="type" use="optional" type="timeoutBehaviorType" default="exception"/> <xs:attribute name="properties" use="optional" default=""/> <xs:attribute name="propertySeparator" use="optional" default=","/> </xs:complexType> </xs:element> <xs:simpleType name="timeoutBehaviorType"> <xs:restriction base="xs:string"> <xs:enumeration value="noop" /> <xs:enumeration value="exception" /> <xs:enumeration value="localReads" /> <xs:enumeration value="localReadsAndExceptionOnWrite" /> </xs:restriction> </xs:simpleType> <xs:simpleType name="monitoringType"> <xs:restriction base="xs:string"> <xs:enumeration value="autodetect"/> <xs:enumeration value="on"/> <xs:enumeration value="off"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="pinningStoreType"> <xs:restriction base="xs:string"> <xs:enumeration value="localMemory" /> <xs:enumeration value="inCache" /> </xs:restriction> </xs:simpleType> <xs:simpleType name="terracottaCacheValueType"> <xs:restriction base="xs:string"> <xs:enumeration value="serialization" /> <xs:enumeration value="identity" /> </xs:restriction> </xs:simpleType> <xs:simpleType name="transactionalMode"> <xs:restriction base="xs:string"> <xs:enumeration value="off"/> <xs:enumeration value="xa_strict"/> <xs:enumeration value="xa"/> <xs:enumeration value="local"/> </xs:restriction> </xs:simpleType> <xs:element name="cacheWriter"> <xs:complexType> <xs:sequence > <xs:element minOccurs="0" maxOccurs="1" ref="cacheWriterFactory"/> </xs:sequence> <xs:attribute name="writeMode" use="optional" type="writeModeType" default="write-through"/> <xs:attribute name="notifyListenersOnException" use="optional" type="xs:boolean" default="false"/> <xs:attribute name="minWriteDelay" use="optional" type="xs:nonNegativeInteger" default="1"/> <xs:attribute name="maxWriteDelay" use="optional" type="xs:nonNegativeInteger" default="1"/> <xs:attribute name="rateLimitPerSecond" use="optional" type="xs:nonNegativeInteger" default="0"/> <xs:attribute name="writeCoalescing" use="optional" type="xs:boolean" default="false"/> <xs:attribute name="writeBatching" use="optional" type="xs:boolean" default="false"/> <xs:attribute name="writeBatchSize" use="optional" type="xs:positiveInteger" default="1"/> <xs:attribute name="retryAttempts" use="optional" type="xs:nonNegativeInteger" default="0"/> <xs:attribute name="retryAttemptDelaySeconds" use="optional" type="xs:nonNegativeInteger" default="1"/> <xs:attribute name="writeBehindConcurrency" use="optional" type="xs:nonNegativeInteger" default="1"/> <xs:attribute name="writeBehindMaxQueueSize" use="optional" type="xs:nonNegativeInteger" default="0"/> </xs:complexType> </xs:element> <xs:simpleType name="writeModeType"> <xs:restriction base="xs:string"> <xs:enumeration value="write-through" /> <xs:enumeration value="write-behind" /> </xs:restriction> </xs:simpleType> <xs:element name="cacheWriterFactory"> <xs:complexType> <xs:attribute name="class" use="required"/> <xs:attribute name="properties" use="optional"/> <xs:attribute name="propertySeparator" use="optional"/> </xs:complexType> </xs:element> <xs:element name="copyStrategy"> <xs:complexType> <xs:attribute name="class" use="required" type="xs:string" /> </xs:complexType> </xs:element> <xs:element name="elementValueComparator"> <xs:complexType> <xs:attribute name="class" use="required" type="xs:string" /> </xs:complexType> </xs:element> <xs:element name="sizeOfPolicy"> <xs:complexType> <xs:attribute name="maxDepth" use="required" type="xs:integer" /> <xs:attribute name="maxDepthExceededBehavior" use="optional" default="continue" type="maxDepthExceededBehavior" /> </xs:complexType> </xs:element> <xs:element name="persistence"> <xs:complexType> <xs:attribute name="strategy" use="required" type="persistenceStrategy"/> <xs:attribute name="synchronousWrites" use="optional" default="false" type="xs:boolean"/> </xs:complexType> </xs:element> <xs:simpleType name="persistenceStrategy"> <xs:restriction base="xs:string"> <xs:enumeration value="localTempSwap"/> <xs:enumeration value="localRestartable"/> <xs:enumeration value="none"/> <xs:enumeration value="distributed"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="maxDepthExceededBehavior"> <xs:restriction base="xs:string"> <xs:enumeration value="continue"/> <xs:enumeration value="abort"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="notificationScope"> <xs:restriction base="xs:string"> <xs:enumeration value="local"/> <xs:enumeration value="remote"/> <xs:enumeration value="all"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="memoryUnit"> <xs:restriction base="xs:token"> <xs:pattern value="[0-9]+[bBkKmMgG]?"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="memoryUnitOrPercentage"> <xs:restriction base="xs:token"> <xs:pattern value="([0-9]+[bBkKmMgG]?|100%|[0-9]{1,2}%)"/> </xs:restriction> </xs:simpleType> </xs:schema>
log4j.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" > <appender name="console" class="org.apache.log4j.ConsoleAppender" > <layout class="org.apache.log4j.PatternLayout" > <!-- Pattern to output the caller's file name and line number --> <param name="ConversionPattern" value="%d %p %t %c - %m%n" /> </layout> </appender> <appender name="rollingFileSys" class="org.apache.log4j.RollingFileAppender" > <param name="file" value="/ylddata/log/vehiclecontrol/VehicleControl_system.log" /> <param name="MaxFileSize" value="10MB" /> <param name="MaxBackupIndex" value="10" /> <layout class="org.apache.log4j.PatternLayout" > <param name="ConversionPattern" value="%d %p %t %c - %m%n" /> </layout> </appender> <appender name="rollingFile" class="org.apache.log4j.RollingFileAppender" > <param name="file" value="/ylddata/log/vehiclecontrol/VehicleControl.log" /> <param name="MaxFileSize" value="10MB" /> <param name="MaxBackupIndex" value="100" /> <layout class="org.apache.log4j.PatternLayout" > <param name="ConversionPattern" value="%d %p %t %c - %m%n" /> </layout> </appender> <logger name="com.baoy.cn" additivity="false"> <level value="debug"/> <appender-ref ref="console" /> <appender-ref ref="rollingFile" /> </logger> <logger name="java.sql" additivity="false"> <level value="warn"/> <appender-ref ref="rollingFileSys" /> </logger> <logger name="com.opensymphony.xwork2" additivity="false"> <level value="warn"/> <appender-ref ref="rollingFileSys" /> </logger> <logger name="org.apache.struts2" additivity="false"> <level value="warn"/> <appender-ref ref="rollingFileSys" /> </logger> <logger name="org.apache" additivity="false"> <level value="warn"/> <appender-ref ref="rollingFileSys" /> </logger> <root> <priority value="warn" /> <appender-ref ref="rollingFileSys" /> </root> </log4j:configuration>