休眠 - 没有活动事务,保存无效

时间:2014-08-14 15:48:43

标签: java spring hibernate

我正在使用 @Transactional 而不是创建 TransactionManager 对象并进行调用。有人可以说明为什么我会收到此 HibernateException:如果没有活动交易,保存无效

对于sessionFactory和TransactionManager

Bean

<bean id="sessionFactory"
          class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="configLocation" value="classpath:hibernate.cfg.xml"/>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
</bean>
<bean id="transactionManager"
          class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
</bean>

UserServiceImpl.java

@Service("userService")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Override
    @Transactional
    public void addUser(User user) {
        userDao.addUser(user);
    }
}

UserDaoImpl.java

@Repository("userDao")
public class UserDaoImpl implements UserDao {

    @Autowired
    private SessionFactory sessionFactory;

    @Override
    public void addUser(User user) {
        sessionFactory.getCurrentSession().save(user);
    }
}

堆栈跟踪

org.hibernate.HibernateException: save is not valid without active transaction
at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:348)
at com.sun.proxy.$Proxy27.save(Unknown Source)
at com.hemanths.expense.manager.hibernate.dao.impl.UserDaoImpl.addUser(UserDaoImpl.java:19)
at com.hemanths.expense.manager.service.impl.UserServiceImpl.addUser(UserServiceImpl.java:21)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)

Hibernate.hbm.xml

<hibernate-configuration>

    <session-factory>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hibernate.current_session_context_class">thread</property>
        <property name="connection.url">jdbc:mysql://127.0.0.1:3306/emanager</property>
        <property name="connection.username">root</property>
        <property name="connection.password">password</property>
        <property name="hibernate.c3p0.min_size">5</property>
        <property name="hibernate.c3p0.max_size">20</property>

        <mapping class="com.hemanths.expense.manager.hibernate.entity.User"/>
    </session-factory>

</hibernate-configuration>

1 个答案:

答案 0 :(得分:3)

删除

<property name="hibernate.current_session_context_class">thread</property>

并尝试