TransactionException: The transaction was not started successfully.

I have a 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();
    }
}

he calls out

@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;

    }

}

in browser I am trying to access this link

And finally, I get the following stacktrace command:

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)

I have the following configuration:

<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>

How to solve this problem?

+4
source share
2 answers

You should not do session.getTransaction().commit();this, @transactional will take care of this. Remove it, everything will be fine.

+10
source

where do you start the transaction. I do not see this line session.beginTrainsaction (); as soon as you start a transaction, then you can commit and roll back

0
source

Source: https://habr.com/ru/post/1547782/


All Articles