简体   繁体   中英

Java Hibernate save an object and update a different object using the same session in the same transaction only update and not save

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM