【问题标题】:delete query in JPA2 with related entities删除 JPA2 中具有相关实体的查询
【发布时间】:2011-08-04 09:02:39
【问题描述】:

我正在尝试批量删除

@NamedQuery(name=CalcData.DELETE, 
query="delete from CalcData as model where model.dataLocation.locCountries = :locCountries and model.locPeriod= :locPeriod")

问题是hibernate把它翻译成

Hibernate: 
delete 
from
    smart_rise.Calc_Data cross 
join
    smart_rise.Data_Location datalocati1_ 
where
    CountryID=? 
    and Period=?

这会在执行命名查询时引发异常

=== 2011-08-04 10:53:30,719 [l0-6] ERROR JDBCExceptionReporter - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'cross join smart_rise.Data_Location datalocati1_ where CountryID=6 and Period=10' at line 1
=== 2011-08-04 10:53:30,719 [l0-6] ERROR PeriodsDMI - org.hibernate.exception.SQLGrammarException: could not execute update query
javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not execute update query
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1214)

知道出了什么问题吗?

谢谢你, 兹达里

【问题讨论】:

    标签: hibernate jpa-2.0


    【解决方案1】:

    您不能通过连接删除。

    如果locCountries 是索引集合尝试子查询:

    delete from CalcData as model 
    where :locCountries in indicies(model.dataLocation.locCountries)
    and model.locPeriod= :locPeriod
    

    如果没有:

    delete from CalcData as model 
    where model.id not in (select id from CalcData as m where model.dataLocation.locCountries = :locCountries  and model.locPeriod= :locPeriod
    )
    

    问候。

    【讨论】:

    • 您好,感谢您的快速答复。我使用了Hibernate: delete from smart_rise.Calc_Data where ID in (select calcdata1_.ID from smart_rise.Calc_Data calcdata1_ cross join smart_rise.Data_Location datalocati2_ where smart_rise.Calc_Data.LocationID=datalocati2_.ID and datalocati2_.CountryID=? and smart_rise.Calc_Data.Period=? ),结果却出现了异常Caused by: java.sql.SQLException: You can't specify target table 'Calc_Data' for update in FROM clause at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073)
    • 这在 MySQL 中不起作用,因为它不允许您从 select 子句中使用的实体中删除
    • 对我来说,如果它仍然存在于 Hibernate 中,那么它就是一个错误,即使部分记录在案(尽管对于 HQL)。规范没有为此提供任何规定,因为它应该可以工作,如 JPA 规范 2.1 §4.10 中描述的批量更新所述,本段引用了第 4.5 节中描述的 where_clause。
    • 反对者,想发表评论吗?我很困惑为什么-1
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-26
    • 1970-01-01
    • 2021-04-21
    相关资源
    最近更新 更多