gpt4 book ai didi

java - Hibernate hql,在同一个查询中执行多个更新语句

转载 作者:IT王子 更新时间:2023-10-28 23:49:06 25 4
gpt4 key购买 nike

我想在 hibernate Hql 的同一个查询中执行多个更新语句。如下:

hql = " update Table1 set prob1=null where id=:id1; "
+ " delete from Table2 where id =:id2 ";
...
query.executeUpdate();

在同一个 executeUpdate 调用中,我想更新 Table1 中的记录并从 Table2 中删除记录。

这可能吗?

最佳答案

in the same executeUpdate call I want to update records in Table1 and delete records from Table2.

Is that possible?

executeUpdate() 执行单个更新查询。所以,不,你不能这样做。您必须执行与要更新/删除的表一样多的更新查询。此外,如果您将查询分开,它会使代码更清晰:

  • 查询更易阅读,参数设置易读且不易出错。
  • 要调试查询执行,如果查询在自己的executeUpdate()
  • 中一一处理,会更容易理解

这并不意味着查询必须强制一个一个地传输。
批处理是 Hibernate 提供的一项功能,用于在您想要执行多个查询时提高性能。您必须启用该功能才能使用它。hibernate.jdbc.batch_size 属性必须设置一个合适的值。

If you are undertaking batch processing you will need to enable the use of JDBC batching. This is absolutely essential if you want to achieve optimal performance. Set the JDBC batch size to a reasonable number (10-50, for example):

hibernate.jdbc.batch_size 20 Hibernate disables insert batching at the JDBC level transparently if you use an identity identifier generator.

除了来自official documentation :

Hibernate disables insert batching at the JDBC level transparently if you use an identity identifier generator.

尽管如此,在您的情况下,这将毫无用处,因为正如 Dragan Bozanovic 解释的那样,您在查询中更新/删除了不同的表。因此,它将创建与查询表一样多的批处理执行。
因此,您应该单独执行每个查询。当你认为它应该是时,只需 commit() 事务:

hql = "update Table1 set prob1=null where id=:id1;"
...
query.setParameter("id1",...);
query.executeUpdate();
hql = "delete from Table2 where id =:id2";
...
query.executeUpdate();
query.setParameter("id2",...);
..
tx.commit();

关于java - Hibernate hql,在同一个查询中执行多个更新语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39033896/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com