Reputation: 51
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.
Upvotes: 0
Views: 675
Reputation: 311
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();
}
}
Upvotes: 1
Reputation: 1128
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
Upvotes: 0