Reputation: 336
I declared Spring Beans in my beans.xml:
<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 and 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;
}
If I use sessionFactory and dataSource beans separately they work well. A also have DAO class:
@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);
}
I don't open the sessions because I want to force Spring to do this. I have Service class with method:
@Override
@Transactional
public void create(Item item) {
dao.create(item);
}
When I call it, I have the exception:
org.hibernate.HibernateException: save is not valid without active transaction
I've done like this tutorial tells. Where is my mistake?
Upvotes: 3
Views: 1069
Reputation: 1251
Try to remove props.put("hibernate.current_session_context_class", "thread")
from your sessionFactory configuration. When you are using Spring managed transactions, you don't need it. Let me know if that works.
Upvotes: 2
Reputation: 11
When I have come across this before it is due to whether Spring is using CGLib or Javassist to augment your class to provide transactionality. if I remember correctly if you only have Javassist in then the class that Spring needs to create the proxy on in order to implement the Transactional annotation must implement an interface.
Upvotes: 0