简体   繁体   English

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

[英]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.产品和订单是 2 种不同的 object 类型。 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.您可能因为没有调用t.begin方法而忘记了开始您的事务。 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-catch 语句存在一些问题,因为 factory.openSession 和 session.beginTransaction 应该在 try 块内,因为两者都会引发异常。 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.通常我使用persist将新条目保存到数据库中。

By the way, I encourage you to use the try-with-resource to avoid adding the finally block at the end顺便说一句,我鼓励你使用try-with-resource来避免在最后添加 finally 块

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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