0

I followed this tutorial mykong in order to use hibernate with mysql.

My problem is that when I launch the program I am getting this exception org.hibernate.TransactionException: Transaction not successfully started".

So I tried to use session.persist(Object) and session.flush() instead of session.save(Object) and session.getTransaction().commit(). Now I am not getting any exception but the object is not saved in the database. logs show the request

Hibernate: insert into stock (STOCK_CODE, STOCK_NAME) values (?, ?)

Could someone help me with this ?

            session = HibernateUtil.getSessionFactory().openSession();

        Stock stock = new Stock();

        stock.setStockCode("4715");
        stock.setStockName("GENM");

        session.persist(stock);

        session.flush();

        session.getTransaction().commit();

        session.close();
4
  • You need to commit the transaction as well. Flushing the session does not commit your data. Commented Aug 27, 2018 at 10:20
  • still getting the same exception Commented Aug 27, 2018 at 10:53
  • can you share where you have started the transaction and committed the transaction? Commented Aug 27, 2018 at 11:07
  • I added the code to my post, but as I said I followed the mykong basic tutorial. Commented Aug 27, 2018 at 11:09

1 Answer 1

1

You're trying to commit a transaction that you haven't even started, as you're missing

session.beginTransaction();

in your code.

As per the web site above you must start a session, then start the transaction in the session, make your edits, save the edited object into session and then commit the transaction. Your flush is also causing issues, as you flush your session before even saving or committing it.

    Session session = HibernateUtil.getSessionFactory().openSession();

    session.beginTransaction();
    Stock stock = new Stock();

    stock.setStockCode("4715");
    stock.setStockName("GENM");

    session.save(stock);
    session.getTransaction().commit();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.