struts2.3.16.1,hibernate4.2.10final,spring3.2版本整合在一起的配置,搞了十几年java还贴这玩意有点丢人,但是搭配这几个框架着实让我忙活了一天,主要是hibernate的高版本需要spring4我不知道,这些年都在用mybatis,以前觉得hibernate特别吃内存,现在跑起来性能好像还不错,具体也没有用性能压力工具去测试。
maven pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>ssh</groupId> <artifactId>ssh</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <org.springframework.version>3.2.6.RELEASE</org.springframework.version> <org.hibernate.version>4.2.10.Final</org.hibernate.version> <org.aspectj-version>1.6.10</org.aspectj-version> <org.slf4j-version>1.6.6</org.slf4j-version> </properties> <!-- <repositories> <repository> <id>Java.Net</id> <url>http://download.java.net/maven/2/</url> </repository> <repository> <id>JBoss repository</id> <url>http://repository.jboss.com/maven2/</url> </repository> <repository> <id>maven</id> <url>http://repo1.maven.org/maven2/</url> </repository> </repositories> --> <build> <sourceDirectory>src</sourceDirectory> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.7</source> <target>1.7</target> </configuration> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>2.3</version> <configuration> <warSourceDirectory>WebContent</warSourceDirectory> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>${org.aspectj-version}</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>${org.aspectj-version}</version> </dependency> <!-- Commons --> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.1.1</version> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging-api</artifactId> <version>1.1</version> </dependency> <dependency> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> <version>3.2</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.2.2</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.0.1</version> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>commons-pool</groupId> <artifactId>commons-pool</artifactId> <version>1.5.6</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.15</version> <exclusions> <exclusion> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> </exclusion> <exclusion> <groupId>javax.jms</groupId> <artifactId>jms</artifactId> </exclusion> <exclusion> <groupId>com.sun.jdmk</groupId> <artifactId>jmxtools</artifactId> </exclusion> <exclusion> <groupId>com.sun.jmx</groupId> <artifactId>jmxri</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.27</version> </dependency> <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>2.2.2</version> </dependency> <dependency> <groupId>asm</groupId> <artifactId>asm</artifactId> <version>3.3.1</version> </dependency> <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>1.0.0.GA</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>4.3.1.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${org.hibernate.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>${org.hibernate.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-ehcache</artifactId> <version>${org.hibernate.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.5</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.5</version> </dependency> <!-- Struts 2 --> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-core</artifactId> <version>2.3.16.1</version> </dependency> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-spring-plugin</artifactId> <version>2.3.16.1</version> </dependency> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-json-plugin</artifactId> <version>2.3.16.1</version> </dependency> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-convention-plugin</artifactId> <version>2.3.16.1</version> </dependency> </dependencies> </project>
spring的配置参数文件application-context.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:aop="http://www.springframework.org/schema/aop" 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-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd" default-autowire="byName"> <context:annotation-config /> <context:property-placeholder location="classpath:jdbc.properties" /> <aop:aspectj-autoproxy /> <context:component-scan base-package="com.xx"></context:component-scan> <bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="${jdbc.driverClassName}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <property name="validationQuery" value="select 1"></property> <property name="initialSize" value="10"/> <!--maxActive: 最大连接数量 0代表无限制--> <property name="maxActive" value="200"/> <!--maxIdle: 最大空闲连接--> <property name="maxIdle" value="200"/> <!--minIdle: 最小空闲连接--> <property name="minIdle" value="5"/> <property name="testWhileIdle" value="true"/> <!--maxWait: 超时等待时间以毫秒为单位 1000等于60秒--> <property name="maxWait" value="1000"/> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> <!-- <prop key="hibernate.cache.region.factory_class">org.hibernate.cache.EhCacheRegionFactory</prop> <prop key="hibernate.cache.use_second_level_cache">true</prop> <prop key="hibernate.cache.use_query_cache">true</prop> <prop key="hibernate.cache.use_structured_entries">true</prop> <prop key="hibernate.cache.provider_configuration_file_resource_path">WEB-INF/classes/ehcache.xml</prop> --> <!-- 用到SessionFactory.getCurrentSession()的话必须配置下面的配置参数,另外不要手动session.close()--> <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</prop> </props> </property> <property name="packagesToScan"> <list> <value>com.xx.entity</value> </list> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <tx:annotation-driven transaction-manager="transactionManager"/> <!-- <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="get*" read-only="true" propagation="REQUIRED" /> <tx:method name="find*" read-only="true" propagation="REQUIRED" /> <tx:method name="query*" read-only="true" propagation="REQUIRED" /> <tx:method name="list*" read-only="true" propagation="REQUIRED" /> <tx:method name="isExist*" read-only="true" propagation="REQUIRED" /> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="create*" propagation="REQUIRED" /> <tx:method name="del*" propagation="REQUIRED" /> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="*" propagation="REQUIRED" /> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut expression="execution(* com.xx.framework.dao..*.*(..))" id="bussinessService" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="bussinessService" /> </aop:config> <aop:config> <aop:pointcut expression="execution(* com.xx.dao..*.*(..))" id="bussinessService1" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="bussinessService1" /> </aop:config> --> </beans>
strutsxml ,采用的是零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.i18n.reload" value="false" /> <constant name="struts.devMode" value="true" /> <constant name="struts.custom.i18n.resources" value="globalMessages" /> <constant name="struts.action.extension" value="action,," /> <!-- 零配置相关 --> <constant name="struts.convention.action.disableScanning" value="false"/> <constant name="struts.convention.default.parent.package" value="default"/> <!-- struts2 零配置返回结果的默认寻找目录 --> <constant name="struts.convention.result.path" value="/WEB-INF/views" /> <!-- struts2 零配置的默认action寻找目录,以下设定为package名称包含actions的才会搜索识别 --> <constant name="struts.convention.package.locators" value="actions" /> <constant name="struts.convention.exclude.packages" value="org.apache.struts.*,org.apache.struts2.*,org.springframework.web.struts.*,org.springframework.web.struts2.*,org.hibernate."/> <package name="default" extends="struts-default,json-default" namespace="/"> </package> </struts>
Hibernate4以后spring貌似就不太管它了,需要自己处理事务等等操作,也没有了DaoSupport类支持,自己胡乱写的BaseDAO基础类,有点简单:
package com.xx.framework.dao; import java.io.Serializable; import java.util.List; import javax.annotation.Resource; import org.apache.log4j.Logger; import org.hibernate.Criteria; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.criterion.Example; import org.springframework.transaction.annotation.Transactional; @SuppressWarnings("unchecked") public class BaseDAO<T> { protected final Logger logger = Logger.getLogger(getClass()); @Resource protected SessionFactory sessionFactory; /** * 插入实体类的泛型方法 * @param pojo 实体类信息 * @return */ @Transactional public Serializable insert(T pojo) throws HibernateException{ Session session = null; Serializable result = null; try { session = sessionFactory.getCurrentSession(); result = (Serializable) session.save(pojo); } catch (Exception e) { logger.error(e.getMessage(), e); throw new HibernateException(e); } return result; } /** * 修改实体类 * @param pojo * @return */ @Transactional public boolean update(T pojo) { Session session = null; boolean result = false; try { session = sessionFactory.getCurrentSession(); session.update(pojo); result = true; } catch (Exception e) { logger.error(e.getMessage(), e); } return result; } @Transactional public boolean delete(T pojo) { Session session = null; boolean result = false; try { session = sessionFactory.getCurrentSession(); session.delete(pojo); result = true; } catch (Exception e) { logger.error(e.getMessage(), e); } finally { } return result; } public T findById(Class<?> c,Serializable id) { Session session = null; T result = null; try { session = sessionFactory.getCurrentSession(); result = (T) session.get(c, id); } catch (Exception e) { logger.error(e.getMessage(), e); } return result; } public List<T> queryForPage(String hql, int pageIndex, int pageSize) { List<T> result = null; Session session = null; try { session = sessionFactory.getCurrentSession(); Query q = session.createQuery(hql); q.setFirstResult((pageIndex - 1) * pageSize); q.setMaxResults(pageSize); result = q.list(); } catch (Exception e) { logger.error(e.getMessage(), e); } return result; } public List<T> queryForPage(String hql,int pageIndex, int pageSize,final Object... objects) { List<T> result = null; Session session = null; try { session = sessionFactory.getCurrentSession(); Query q = session.createQuery(hql); for (int i = 0; i < objects.length; i++) { q.setParameter(i, objects[i]); } q.setFirstResult((pageIndex - 1) * pageSize); q.setMaxResults(pageSize); result = q.list(); } catch (Exception e) { logger.error(e.getMessage(), e); } return result; } public int queryRecordCount(String hql,final Object... objects) { int result = 0; Session session = null; try { session = sessionFactory.getCurrentSession(); Query q = session.createQuery(hql); for (int i = 0; i < objects.length; i++) { q.setParameter(i, objects[i]); } result = ((Long)q.list().get(0)).intValue(); } catch (Exception e) { logger.error(e.getMessage(), e); } return result; } public List<T> findByExample(Class<?> c,T t) { List<T> result = null; Session session = null; try { session = sessionFactory.getCurrentSession(); Example example = Example.create(t); Criteria criteria = session.createCriteria(c); criteria.add(example); result = criteria.list(); } catch (Exception e) { logger.error(e.getMessage(), e); } return result; } public List<T> listAll(Class<?> c) { List<T> result = null; Session session = null; try { session = sessionFactory.getCurrentSession(); Criteria criteria = session.createCriteria(c); result = criteria.list(); } catch (Exception e) { logger.error(e.getMessage(), e); } return result; } public List<Object[]> findBySql(String sql, final Object... objects) { List<Object[]> result = null; Session session = null; try { session = sessionFactory.getCurrentSession(); Query query = session.createSQLQuery(sql); for (int i = 0; i < objects.length; i++) { query.setParameter(i, objects[i]); } result = query.list(); } catch (Exception e) { logger.error(e.getMessage(), e); } return result; } public List<Object[]> findByHql(String hql, final Object... objects) { List<Object[]> list = null; Session session = null; try { session = sessionFactory.getCurrentSession(); Query query = session.createQuery(hql); for (int i = 0; i < objects.length; i++) { query.setParameter(i, objects[i]); } list = query.list(); } catch (Exception e) { logger.error(e.getMessage(), e); } return list; } }
Struts2公共基础action类
package com.shinowit.framework.action; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; import org.apache.struts2.interceptor.ServletRequestAware; import org.apache.struts2.interceptor.ServletResponseAware; import org.apache.struts2.util.ServletContextAware; import com.opensymphony.xwork2.ActionSupport; public class BaseAction extends ActionSupport implements ServletRequestAware, ServletContextAware, ServletResponseAware{ private static final long serialVersionUID = -1040212988363452551L; protected final Logger logger = Logger.getLogger(getClass()); protected HttpServletRequest request; protected ServletContext application; protected HttpServletResponse response; protected HttpSession session; @Override public void setServletRequest(HttpServletRequest request) { this.request = request; session = this.request.getSession(); } @Override public void setServletResponse(HttpServletResponse response) { this.response = response; } @Override public void setServletContext(ServletContext application) { this.application = application; } }
Struts2 Action代码
package com.shinowit.actions; import java.util.List; import javax.annotation.Resource; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.Namespace; import org.apache.struts2.convention.annotation.ParentPackage; import org.apache.struts2.convention.annotation.Result; import org.springframework.context.annotation.Scope; import com.xx.dao.UserDao; import com.xx.entity.User; import com.xxframework.action.BaseAction; @Namespace("/") @ParentPackage("default") @Scope("prototype") public class UserAction extends BaseAction { private static final long serialVersionUID = 1L; @Resource private UserDao userDao; private User user; private List<User> users; public String test(){ user=new User(); user.setUserName("test"); userDao.insert(user); return "success"; } @Action(value="find",results={@Result(name="success",location="test.jsp"), @Result(name="failure",location="/index.jsp")}) public String find(){ user=userDao.findById(user.getUserId()); return "success"; } @Action(value="page",results={@Result(name="success",location="testpage.jsp"), @Result(name="failure",location="/index.jsp")}) public String listPage(){ users=userDao.queryForPage("from User",1, 2); return "success"; } @Action(value="pagejson",results={@Result(type="json",name="success")}) public String listPageJson(){ users=userDao.queryForPage("from User",1, 2); return "success"; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public List<User> getUsers() { return users; } }
-------------------------------------------------------------------------------------
因为有JPA对象的延迟加载,所以hibernate的session改成了通过在web.xml里面定义filter去打开和关闭session,注意务必要把hibernate的opensessioninviewfitler写在struts2的filter前面,另外spring的配置参数文件中务必写上<prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</prop> 才可以实现延迟加载。