0

What I'm trying to do is when the customer order a product the order will be save to the DB and that product will be updated.

Session session = factory.openSession();
Transaction t = session.beginTransaction();

        try {
            session.update(product);
            session.save(order);
            t.commit();
        }
        catch (Exception e) {
            t.rollback();
        }
        finally {
            session.close();
        }

The product and the order are 2 different object type. I got no exception when running this code but only the product got updated, the order was not saved.

Sorry for my bad English.

1
  • It's possible that I'm missing context here. How are your entities configured? Are they related to the same data source, or at least, same transaction manager? Can you attach the entities involved and hibernate configuration to your question? Commented Nov 14, 2019 at 11:42

2 Answers 2

1

You probably forgot to start your transaction, by not calling the t.begin method. Also, there are some problems with your try-catch statement, since the factory.openSession and session.beginTransaction should be inside the try block, since both can raise exceptions. Try the following example code:

Session session = null;
Transaction t = null;

try {
  session = factory.openSession();
  t = session.beginTransaction();
  t.begin()

  session.update(product);
  session.save(order);

  t.commit();
}
catch (Exception e) {
  if (t != null) {
    t.rollback();
  }
}
finally {
  if (session != null) {
    session.close();
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Sorry still not work, when I add the t.begin() both update and save not work but still no exception.
without t.begin() and run only update or save it work, but with both of them only the update work. product and order has 2 different types (product's type is Product and order's type is Order)
0

Usually I use persist for saving new entries to the database.

By the way, I encourage you to use the try-with-resource to avoid adding the finally block at the end

1 Comment

@Thạch Hải Đăng What you mean by the product will be updated. If you have a List of products in the Customer you need the proper mapping also you need to add the product to the list and then save the customer.

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.