我是冬眠和春天的初学者。我已经了解hibernate事务划分(至少我认为是这样)。但是在编写了一些这样的方法之后:
sessionFactory.getCurrentSession().beginTransaction();
//do something here
sessionFactory.getCurrentSession().endTransaction();
我开始想避免它,想让它在我的方法之外自动完成,这样我只写“//在这里做点什么”部分。我已经阅读了TransactionProxyFactoryBean,并认为xml配置非常长,必须对我要使之成为事务性的每个类重复配置,因此如果可能,我希望避免使用它。
我试图使用@Transactional,但它根本不起作用。我的applicationContext.xml中有这些行
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:hibernate.cfg.xml" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="dataSource" ref="dataSource" />
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
我已经用@Transactional标记了我的服务类,但是我总是得到“没有活动事务xxx是无效的”。
下面是给我一个错误的示例代码(在单元测试btw中运行):
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations =
{
"classpath:applicationContext.xml"
})
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
public class UserServiceTest
{
@Resource
private UserService userService;
@Test
public void testAddUser()
{
User us = new User();
us.setName("any name");
userService.addUser(us);
}
}
在这种情况下,确切的错误消息是:“org.hibernate.HibernateException:save在没有活动事务的情况下无效”。
更新
:我尝试从外部单元测试(即从实际的web应用程序)调用userService.addUser()方法,也得到了相同的错误。
这是我的hibernate.cfg.xml:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
<!-- all my mapping resources here -->
</session-factory>
</hibernate-configuration>
userService类用@Transactional标记。我正在使用Hibernate3.3.2和Spring2.5.6。
我能给你一些建议吗?