我创建了一个Spring(4.0.2)+ JPA / hibernate(4.3.4)项目。我试图测试它的提交和回滚。在我的服务层测试回滚时,我试图有一个事务,保存第一个对象然后抛出错误并保存第二个对象,....在jboss中它按预期工作,即使第一个对象没有保存在DB但在tomcat中它保存了第一个对象,即使在服务方法中引发了错误...我的示例代码在
之下<context:component-scan base-package="com.pkg.*" />
<mvc:annotation-driven />
<jee:jndi-lookup id="dataSource" jndi-name="java:jboss/datasources/jbpmDS" />
<!-- <jee:jndi-lookup id="dataSource" jndi-name="jdbc/jBPMDS" /> -->
<bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="mainPU"/>
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
</bean>
<bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<!-- <property name="database" value="ORACLE" /> -->
<property name="showSql" value="true" />
<property name="generateDdl" value="true" />
<property name="databasePlatform" value="org.hibernate.dialect.H2Dialect" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" >
<property name="entityManagerFactory" ref="emf" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
我的服务类
@Transactional(propagation=Propagation.REQUIRES_NEW,rollbackFor=Exception.class)
public void addPersonException() throws Exception{
try{
Person p=new Person();
p.setAge(20);
p.setFirstName("Exception 1");
p.setLastName("Exception Last Name 1");
commonDao.insert(p);
String x=null;
System.out.println(x.indexOf("1"));
Person p2=new Person();
p2.setAge(20);
p2.setFirstName("Exception 2");
p2.setLastName("Exception Last Name 2");
commonDao.insert(p2);
}catch(Exception e){
System.out.println("rollback added");
throw e;
}
}
CommonDao
@Transactional(propagation = Propagation.SUPPORTS)
public boolean insert(Object o){
em.persist(o);
}
知道为什么这不能在tomcat中运行吗? 我是否需要将JTA用于tomcat?