TransactionException:事务未成功启动

时间:2014-07-09 15:37:03

标签: java spring hibernate session transactions

我跟随dao:

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

    @Autowired
    private SessionFactory sessionFactory;

    @Transactional
    public void add(User user) {
        Session session = sessionFactory.getCurrentSession();
        session.save(user);
        session.getTransaction().commit();
    }
}

调用
@Controller
public class HomeController {    

    @Autowired
    private UserDao userDao;


    @RequestMapping(value = "/test")
    public ModelAndView test() {
        User user = new User();
        user.setName("34r");

        userDao.add(user);

        ModelAndView model = new ModelAndView("home");
        model.addObject("userList", null);
        return model;

    }

}
浏览器中的

我尝试访问此链接

最后我得到了以下的堆栈跟踪:

SEVERE: Servlet.service() for servlet [appServlet] in context with path [/SpringMvcHibernateXML] threw exception [Request processing failed; nested exception is org.springframework.transaction.TransactionSystemException: Could not commit Hibernate transaction; nested exception is org.hibernate.TransactionException: Transaction not successfully started] with root cause
org.hibernate.TransactionException: Transaction not successfully started
    at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:172)

我有以下配置:

<bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="classpath:hibernate.cfg.xml" />
    </bean>

    <tx:annotation-driven />
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

如何解决这个问题?

2 个答案:

答案 0 :(得分:11)

你不应该session.getTransaction().commit();这个,@ transnsaction将会照顾它。删除它,你应该没事。

答案 1 :(得分:1)

开始交易的地方。我看不出这一行 session.beginTrainsaction(); 一旦你开始交易,那么只有你可以提交和回滚