【发布时间】:2015-02-09 13:57:57
【问题描述】:
我在 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 bean:
@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 执行此操作。我有带有方法的服务类:
@Override
@Transactional
public void create(Item item) {
dao.create(item);
}
当我调用它时,我有例外:
org.hibernate.HibernateException: save is not valid without active transaction
我已经像this tutorial 所说的那样做了。我的错在哪里?
【问题讨论】:
-
你注入调用
create(Item item)的类吗? (我投赞成票,所以你有足够的声誉在 cmets 中回答) -
您能否提供
sessionFactory的实现? -
我当然愿意。我已经更新了我的问题。看看我的 dataSource 和 sessionFactory bean
-
@Transactional 使用 Spring AOP 应用(默认使用 JDK 代理),您的服务是否实现接口?是在声明 create 方法的服务类外部调用 create 吗?
标签: java spring hibernate transactions