首页 > 代码库 > struts2+hibernate-jpa+Spring+maven 整合(2)
struts2+hibernate-jpa+Spring+maven 整合(2)
1.修改pom.xml
1. 添加 slf4j-api
<dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.0</version> </dependency>
2.添加 spring-orm
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>3.0.5.RELEASE</version> </dependency>
3.加入hibernate
<dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.7.2</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>3.6.10.Final</version> <exclusions> <exclusion> <artifactId>slf4j-api</artifactId> <groupId>org.slf4j</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>3.6.10.Final</version> <exclusions> <exclusion> <artifactId>slf4j-api</artifactId> <groupId>org.slf4j</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.21</version> </dependency> <dependency> <groupId>com.alibaba.druid</groupId> <artifactId>druid-wrapper</artifactId> <version>0.2.9</version> </dependency>
最终pom文件如下:
<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>cc.jorcen.msai</groupId> <artifactId>mport</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <name /> <description /> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.0</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>3.0.5.RELEASE</version> </dependency> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-spring-plugin</artifactId> <version>2.3.16</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.7.2</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>3.6.10.Final</version> <exclusions> <exclusion> <artifactId>slf4j-api</artifactId> <groupId>org.slf4j</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>3.6.10.Final</version> <exclusions> <exclusion> <artifactId>slf4j-api</artifactId> <groupId>org.slf4j</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.21</version> </dependency> <dependency> <groupId>com.alibaba.druid</groupId> <artifactId>druid-wrapper</artifactId> <version>0.2.9</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> </dependency> <!-- J2EE COMMONS --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.glassfish</groupId> <artifactId>javax.annotation</artifactId> <version>3.0.1</version> </dependency> <dependency> <groupId>org.glassfish</groupId> <artifactId>javax.ejb</artifactId> <version>3.0.1</version> </dependency> <dependency> <groupId>org.glassfish</groupId> <artifactId>javax.servlet</artifactId> <version>3.0.1</version> </dependency> </dependencies> <build> <plugins> <plugin> <artifactId>maven-war-plugin</artifactId> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> </plugins> </build> </project>
添加 spring-dataSource.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- JNDI方式配置数据源 --> <!-- <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName" value="http://www.mamicode.com/${jndiName}"></property> </bean> --> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:dataSourceConfig.properties</value> </list> </property> </bean> <!-- 配置数据源 --> <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="url" value="${jdbc_url}" /> <property name="username" value="${jdbc_username}" /> <property name="password" value="${jdbc_password}" /> <!-- 初始化连接大小 --> <property name="initialSize" value="1" /> <!-- 连接池最大使用连接数量 --> <property name="maxActive" value="20" /> <!-- 连接池最大空闲 --> <property name="maxIdle" value="20" /> <!-- 连接池最小空闲 --> <property name="minIdle" value="1" /> <!-- 获取连接最大等待时间 --> <property name="maxWait" value="60000" /> <!-- <property name="poolPreparedStatements" value="http://www.mamicode.com/true" /> <property name="maxPoolPreparedStatementPerConnectionSize" value="http://www.mamicode.com/33" /> --> <property name="validationQuery" value="${validationQuery}" /> <property name="testOnBorrow" value="false" /> <property name="testOnReturn" value="false" /> <property name="testWhileIdle" value="true" /> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="60000" /> <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="25200000" /> <!-- 打开removeAbandoned功能 --> <property name="removeAbandoned" value="true" /> <!-- 1800秒,也就是30分钟 --> <property name="removeAbandonedTimeout" value="1800" /> <!-- 关闭abanded连接时输出错误日志 --> <property name="logAbandoned" value="true" /> <!-- 监控数据库 --> <!-- <property name="filters" value="http://www.mamicode.com/stat" /> --> <property name="filters" value="mergeStat" /> </bean> </beans>
添加 spring-jpa.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" xmlns:p="http://www.springframework.org/schema/p" xmlns:cache="http://www.springframework.org/schema/cache" 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 http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.0.xsd"> <!-- 配置实体管理对象 p:persistenceUnitManager-ref="persistenceUnitManager" --> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="persistenceXmlLocation" value="classpath:/META-INF/persistence.xml" /> <property name="dataSource" ref="dataSource" /> <!-- 选配属性 --> <property name="jpaVendorAdapter"> <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"> <property name="database" value="MYSQL" /> <property name="showSql" value="true" /> <property name="generateDdl" value="true" /> <property name="databasePlatform" value="${hibernate.dialect}" /> </bean> </property> </bean> <!--可屏蔽 <bean id="persistenceUnitManager" class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager" p:default-data-source-ref="dataSource" p:persistence-xml-locations="classpath*:META-INF/persistence.xml"> <property name="loadTimeWeaver"> <bean class="org.springframework.instrument.classloading.ReflectiveLoadTimeWeaver"/> </property> </bean> --> <bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory" /> </bean> <tx:annotation-driven transaction-manager="txManager" proxy-target-class="true" /> <!-- 定义使用事务的方法 --> <tx:advice id="txAdvice" transaction-manager="txManager"> <tx:attributes> <tx:method name="add*" propagation="REQUIRED" rollback-for="Throwable" /> <tx:method name="append*" propagation="REQUIRED" rollback-for="Throwable" /> <tx:method name="insert*" propagation="REQUIRED" rollback-for="Throwable" /> <tx:method name="save*" propagation="REQUIRED" rollback-for="Throwable" /> <tx:method name="update*" propagation="REQUIRED" rollback-for="Throwable" /> <tx:method name="modify*" propagation="REQUIRED" rollback-for="Throwable" /> <tx:method name="edit*" propagation="REQUIRED" rollback-for="Throwable" /> <tx:method name="delete*" propagation="REQUIRED" rollback-for="Throwable" /> <tx:method name="remove*" propagation="REQUIRED" rollback-for="Throwable" /> <tx:method name="repair" propagation="REQUIRED" rollback-for="Throwable" /> <tx:method name="delAndRepair" propagation="REQUIRED" rollback-for="Throwable" /> <tx:method name="get*" propagation="SUPPORTS" rollback-for="Throwable" /> <tx:method name="find*" propagation="SUPPORTS" rollback-for="Throwable" /> <tx:method name="load*" propagation="SUPPORTS" rollback-for="Throwable" /> <tx:method name="search*" propagation="SUPPORTS" rollback-for="Throwable" /> <tx:method name="datagrid*" propagation="SUPPORTS" rollback-for="Throwable" /> <tx:method name="*" propagation="SUPPORTS" rollback-for="Throwable" /> </tx:attributes> </tx:advice> <!-- 定义 切入点,使事务在它的切入点内有效 --> <aop:config> <aop:pointcut expression="within(com..*.service..*.impl.*)" id="TXpointcut1" /> <aop:advisor pointcut-ref="TXpointcut1" advice-ref="txAdvice" /> </aop:config> <aop:config> <aop:pointcut expression="within(com..*.service.impl.*)" id="TXpointcut2" /> <aop:advisor pointcut-ref="TXpointcut2" advice-ref="txAdvice" /> </aop:config> </beans>
配置dataSourceConfig.properties文件如下:
#hibernate.dialect=org.hibernate.dialect.OracleDialect #driverClassName=oracle.jdbc.driver.OracleDriver #validationQuery=SELECT 1 FROM DUAL #jdbc_url=jdbc:oracle:thin:@localhost:1521:orcl #jdbc_username=sypro #jdbc_password=sypro hibernate.dialect=org.hibernate.dialect.MySQLDialect driverClassName=com.mysql.jdbc.Driver validationQuery=SELECT 1 jdbc_url=jdbc:mysql://localhost:3306/c_sai?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull jdbc_username=root jdbc_password= #hibernate.dialect=org.hibernate.dialect.SQLServerDialect #driverClassName=net.sourceforge.jtds.jdbc.Driver #validationQuery=SELECT 1 #jdbc_url=jdbc:jtds:sqlserver://127.0.0.1:1433/sy #jdbc_username=sa #jdbc_password=123456 #hibernate.dialect=org.hibernate.dialect.DerbyDialect #driverClassName=org.apache.derby.jdbc.EmbeddedDriver #validationQuery=SELECT 1 #jdbc_url=jdbc:derby:sy;create=true #jdbc_username=sypro #jdbc_password=sypro #jndiName=java:comp/env/dataSourceName hibernate.hbm2ddl.auto=update hibernate.show_sql=true hibernate.format_sql=true sessionInfoName=sessionInfo uploadFieldName=filedata uploadFileMaxSize=20971520 uploadFileExts=txt,rar,zip,doc,docx,xls,xlsx,jpg,jpeg,gif,png,swf,wmv,avi,wma,mp3,mid uploadDirectory=attached
测试类如下:
package com.sai.test.dao.impl; import javax.annotation.Resource; import javax.persistence.EntityManagerFactory; import org.springframework.orm.jpa.JpaTemplate; import org.springframework.orm.jpa.support.JpaDaoSupport; import org.springframework.stereotype.Repository; import com.sai.test.po.TTest; @Repository("TTestDAOImpl") public class TTestDAOImpl extends JpaDaoSupport implements TTestDAO { @Resource public void setMyEntityManagerFactory( EntityManagerFactory entityManagerFactory) { JpaTemplate jpaTemplate = new JpaTemplate(entityManagerFactory); super.setJpaTemplate(jpaTemplate); } @Override public TTest findById(Integer id) { return getJpaTemplate().find(TTest.class, id); } @Override public TTest save(TTest user) { getJpaTemplate().persist(user); return null; } }
service
package com.sai.test.service.impl; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.sai.test.dao.impl.TTestDAO; import com.sai.test.po.TTest; import com.sun.tools.internal.ws.wsdl.document.jaxws.Exception; @Service("TTestServiceImpl") public class TTestServiceImpl implements TTestService { @Resource private TTestDAO dao; @Override public TTest findById(Integer id) { TTest test = dao.findById(id); return test; } @Override public void save(TTest test) { dao.save(test); } @Override public void put(TTest test) { dao.save(test); } @Override public void save2(TTest test) throws Throwable { dao.save(test); if (1 == 1) throw new Throwable("bollback now !"); } }
测试类如下:
package test.jpa.tx; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.sai.test.dao.impl.TTestDAO; import com.sai.test.po.TTest; import com.sai.test.service.impl.TTestService; public class JPA_TX_Test { private static final String PATH = "spring-*.xml"; private static final String APPLICATION = "spring-application-jpa-customDataSource.xml"; private static final ApplicationContext ac = new ClassPathXmlApplicationContext( PATH); TTestService t = (TTestService) ac.getBean("TTestServiceImpl"); @Test public void support() { try { TTestDAO t = (TTestDAO) ac.getBean("TTestDAOImpl"); Object obj = t.findById(1); System.out.println("TTestDAOImpl.findById : "+obj); } catch (Exception e) { e.printStackTrace(); } } @Test public void txSupport() { try { Object obj = t.findById(1); TTest test = new TTest(); test.setUserName("put"); t.put(test); System.out.println("TTestServiceImpl.put : "+obj); } catch (Exception e) { e.printStackTrace(); } } @Test public void txRequired() { try { Object obj = t.findById(1); TTest test = new TTest(); test.setUserName("save"); t.save(test); System.out.println("TTestServiceImpl.save : "+obj); } catch (Exception e) { e.printStackTrace(); } } @Test public void txRequired2() { TTest test = new TTest(); try { test.setUserName("save2"); t.save2(test); } catch (Throwable e) { System.out.println("TTestServiceImpl.save2 : "+test); e.printStackTrace(); } } }
结果如下:
Hibernate: select ttest0_.id as id0_0_, ttest0_.userName as userName0_0_ from c_sai.t_test ttest0_ where ttest0_.id=? TTestDAOImpl.findById : TTest [id=1, userName=2] Hibernate: insert into c_sai.t_test (userName) values (?) TTestServiceImpl.save2 : TTest [id=42, userName=save2] java.lang.Throwable: bollback now ! at com.sai.test.service.impl.TTestServiceImpl.save2(TTestServiceImpl.java:39) at com.sai.test.service.impl.TTestServiceImpl$$FastClassByCGLIB$$ecd6b2c8.invoke(<generated>) at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:191) at org.springframework.aop.framework.Cglib2AopProxy$CglibMethodInvocation.invokeJoinpoint(Cglib2AopProxy.java:688) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:89) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:621) at com.sai.test.service.impl.TTestServiceImpl$$EnhancerByCGLIB$$bd6bd63e.save2(<generated>) at test.jpa.tx.JPA_TX_Test.txRequired2(JPA_TX_Test.java:58) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229) at org.junit.runners.ParentRunner.run(ParentRunner.java:309) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197) Hibernate: select ttest0_.id as id0_0_, ttest0_.userName as userName0_0_ from c_sai.t_test ttest0_ where ttest0_.id=? TTestServiceImpl.put : TTest [id=1, userName=2] Hibernate: select ttest0_.id as id0_0_, ttest0_.userName as userName0_0_ from c_sai.t_test ttest0_ where ttest0_.id=? Hibernate: insert into c_sai.t_test (userName) values (?) TTestServiceImpl.save : TTest [id=1, userName=2]
数据库记录如下:
Id | username |
1 | 2 |
43 | save |
到此,在web.xml里面添加配置:
<filter> <filter-name>encoding</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>encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- OpenEntityManagerInViewFilter--> <filter> <filter-name>Spring OpenEntityManagerInViewFilter</filter-name> <filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class> </filter> <filter-mapping> <filter-name>Spring OpenEntityManagerInViewFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
最终效果如下:
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <!-- contextConfigLocation --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:/spring-*.xml</param-value> </context-param> <filter> <filter-name>encoding</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>encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- OpenEntityManagerInViewFilter --> <filter> <filter-name>Spring OpenEntityManagerInViewFilter </filter-name> <filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class> </filter> <filter-mapping> <filter-name>Spring OpenEntityManagerInViewFilter </filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <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>*.cy</url-pattern> </filter-mapping> <display-name></display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
到此,整合完毕
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。