我正在使用@Transactional注释来测试通过Spring应用程序将一些数据插入到其中一个表中。我的测试成功,但我没有看到任何数据插入到表中。
以下是相关的代码段:
MyTest的:
@TransactionConfiguration(transactionManager="MyTxManager")
@Transactional
public class MyTest {
@Autowired
private DataProvider provider;
@Test
@Transactional
void testInsert() {
Order purchaseOrder = new Order("ID1", "LER", "VDR1", 0, );
provider.addRow(purchaseOrder);
}
}
的DataProvider:
public class DataProvider extends DatabaseProvider {
// some stuff...
@Transactional
public void insertRow(Order purchaseOrder) {
/*
* SessionFactory is got through autowiring
* and is working perfectly fine.
*/
Session session = sessionFactory.getCurrentSession();
// This should save the row into the table - which it doesn't :(
session.save(purchaseOrder);
}
}
信息providers.xml
<bean id="DataProvider" class="com.util.DataProvider">
<property name="sessionFactory" ref="MySessionFactory" />
</bean>
hibernate.xml包含会话工厂的配置
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"
parent="AbstractSessionFactory" depends-on="EnvironmentHelper">
<property name="hibernateProperties">
<props>
<prop key="hibernate.connection.autocommit">true</prop>
<prop key="hibernate.connection.provider_class">com.hibernate.ConnectionPool</prop>
<prop key="hibernate.connection.driver_class">${driverClassName}</prop>
<prop key="hibernate.connection.url">${databaseURL}</prop>
<prop key="hibernate.connection.username">${databaseUsername}</prop>
<prop key="hibernate.connection.password">${databasePassword}</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.default_schema">${databaseDefaultSchema}</prop>
</props>
</property>
</bean>
<!-- Use Spring transactions for Hibernate -->
<tx:annotation-driven transaction-manager="MyTxManager" mode='proxy' proxy-target-class='true'/>
<bean id="MyTxManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="MySessionFactory" />
</bean>
</beans>
答案 0 :(得分:2)
我认为回滚交易的问题。请参见此处defaultRollback方法。 试试这样:
@TransactionConfiguration(transactionManager="MyTxManager", defaultRollback=false)
答案 1 :(得分:1)
你的问题是MyProvider myProviderInstance = new MyProvider();
myProviderInstance 不是由Spring容器维护的,你只是新建它,所以Spring无法对它做任何事情,肯定是事务没有'工作。你应该在Spring applicationcontext.xml中配置bean并用ApplicationtContext加载它,你可以在谷歌之后找到几十个样本。因为你使用Mysql,你应该确保使用innerDB模式或者mysql不支持该事务。
答案 2 :(得分:0)
将行<tx:annotation-driven/>
添加到弹簧配置