gpt4 book ai didi

java - 使用jpa从同一个选择同一个表mariadb的表中删除

转载 作者:可可西里 更新时间:2023-11-01 09:02:09 25 4
gpt4 key购买 nike

我需要在同一个表的操作上从表中删除。JPA 查询是

DELETE  FROM com.model.ElectricityLedgerEntity a 
Where a.elLedgerid IN
(SELECT P.elLedgerid FROM
(SELECT MAX(b.elLedgerid)
FROM com.model.ElectricityLedgerEntity b
WHERE b.accountId='24' and b.ledgerType='Electricity Ledger' and b.postType='ARREARS') P );

我遇到了这个错误:

with root cause org.hibernate.hql.ast.QuerySyntaxException: unexpected token: ( near line 1, column 109 [DELETE FROM com.bcits.bfm.model.ElectricityLedgerEntity a Where a.elLedgerid IN ( SELECT P.elLedgerid FROM ( SELECT MAX(b.elLedgerid) FROM com.bcits.ElectricityLedgerEntity b WHERE b.accountId='24' and b.ledgerType='Electricity Ledger' and b.postType='ARREARS') P ) ] at org.hibernate.hql.ast.QuerySyntaxException.convert(QuerySyntaxException.java:54) at org.hibernate.hql.ast.QuerySyntaxException.convert(QuerySyntaxException.java:47) at org.hibernate.hql.ast.ErrorCounter.throwQueryException(ErrorCounter.java:82) at org.hibernate.hql.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:284)

相同的查询正在 mysql 终端上运行,但这不适用于 jpa。任何人都可以告诉我如何使用 jpa 编写此查询。

最佳答案

我不明白为什么要在最后一个括号之前使用 P...

下面的代码还不够吗?

DELETE  FROM com.model.ElectricityLedgerEntity a 
Where a.elLedgerid IN
(SELECT MAX(b.elLedgerid)
FROM com.model.ElectricityLedgerEntity b
WHERE b.accountId='24' and b.ledgerType='Electricity Ledger' and
b.postType='ARREARS')

绕过 mysql 子查询限制的编辑:

新错误java.sql.SQLException: You can't specify target table 'LEDGER' for update in FROM clause当您将它与 JPA 一起使用时,它在 mysql 中是已知的。这是一个 MySQL 限制。 A recent stackoverflow question about it
简而言之,您不能“直接”更新/删除您在 select 子句中查询的表

现在我明白了为什么您的原始查询执行了多个子查询,这些子查询看似没有必要(虽然它对 mysql 很有用)并且具有“特殊”语法。我不知道在 JPA 中解决这个问题的技巧(我现在很长时间不使用 MySQL DBMS)。

在你那里,我会做两个查询。第一个是您选择预期的最大 elLedgerid 的地方,第二个是您可以删除具有在上一个查询中检索到的 ID 的行的地方。如果你的 sql 模型设计良好,sql 索引放置得当,访问数据库的时间正确,你就不应该有性能问题。

关于java - 使用jpa从同一个选择同一个表mariadb的表中删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38538557/

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