我在beans.xml中声明了Spring Beans:
<context:annotation-config />
<context:component-scan base-package="com.pack"/>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
<property name="dataSource" ref="dataSource"></property>
</bean>
dataSource和sessionFactory beans:
@Bean(name = "dataSource")
public DriverManagerDataSource dataSource() {
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setUsername(userName);
ds.setPassword(password);
ds.setDriverClassName(driverName);
ds.setUrl(url);
return ds;
}
@Bean(name = "sessionFactory")
public LocalSessionFactoryBean localSessionFactoryBean() {
LocalSessionFactoryBean factory = new LocalSessionFactoryBean();
factory.setDataSource(dataSourceConfiguration.dataSource());
Properties props = new Properties();
props.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
props.put("hibernate.hbm2ddl.auto", "update");
props.put("hibernate.current_session_context_class", "thread");
factory.setHibernateProperties(props);
factory.setMappingResources("com/pack/Item.hbm.xml");
return factory;
}
如果我分别使用sessionFactory和dataSource bean,它们运行良好。 A还有DAO类:
@Repository(value = "itemDaoHibernateImpl")
public class ItemDaoHibernateImpl implements ItemDao {
@Resource(name = "sessionFactory")
private SessionFactory factory;
public void setFactory(SessionFactory factory) {
this.factory = factory;
}
public Session session() {
return factory.getCurrentSession();
}
@Override
public void create(Item item) {
session().save(item);
}
我没有打开会话,因为我想强迫Spring这样做。我有Service class with method:
@Override
@Transactional
public void create(Item item) {
dao.create(item);
}
当我打电话时,我有例外:
org.hibernate.HibernateException: save is not valid without active transaction
我完成了像this tutorial所说的那样。我的错误在哪里?
答案 0 :(得分:2)
尝试从sessionFactory配置中删除props.put("hibernate.current_session_context_class", "thread")
。当您使用Spring托管交易时,您并不需要它。如果有效,请告诉我。
答案 1 :(得分:0)
当我遇到这个问题之前,由于Spring是否正在使用CGLib或Javassist来增强您的类以提供事务性。如果我没记错,如果你只有Javassist那么Spring需要创建代理的类来实现Transactional注释必须实现一个接口。