【问题标题】:JPA + Hibernate, bulk delete with IS NULL, SQL command not properly endedJPA + Hibernate,使用 IS NULL 批量删除,SQL 命令未正确结束
【发布时间】:2017-02-15 12:00:08
【问题描述】:

我正在尝试批量删除。

Query queryDeleteEntries = entityManager.createQuery("DELETE from
  Entry r where (r.person.emailAddress like :name) and (r.otherData is null)");
int deletedEntriesCount = queryDeleteEntries.setParameter("name",
  "tester." + emailAddressSuffix).executeUpdate();

我收到一个错误:

Caused by: java.sql.SQLException: ORA-00933: SQL command not properly ended
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112) ~[DatabaseError.class:Oracle JDBC Driver version - "10.2.0.2.0"]

如果没有“and r.otherData is null”,它可以工作,所以我看不出有什么问题?

otherData 是一个列表,它在 Entry 类中以这种方式定义:

@OneToMany(fetch = FetchType.EAGER)
@JoinColumn(name = "ENTRY_ID", referencedColumnName = "ID")
private List<OtherData> otherData;

OtherData(改名)类:

@Entity
@Table(name = "OTHERDATA")
@SequenceGenerator(name = "SEQ", allocationSize = 1, sequenceName = "SEQ_OTHERDATA_ID")
public class OtherData {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ")
    private Long id;

    ...

    @Column(name = "ENTRY_ID")
    private Long entryId;

我不能在列表中使用“is null”吗?

编辑

我尝试使用“size(r.otherData) = 0”和“r.otherData IS EMPTY”,但都导致了相同的异常。

它的作用是:

Query queryDeleteEntries = entityManager.createQuery("DELETE from Entry r where id in "
  + "(select id from Entry r2 where r2.person.emailAddress like :name"
  + " and not exists (select 1 from OtherData a where a.entryId = r2.id))");
int deletedEntriesCount = queryDeleteEntries.setParameter("name", "tester."+emailAddressSuffix).executeUpdate();

但我认为它不应该那么复杂!没有更简单的方法吗?

提前感谢任何提示!

【问题讨论】:

标签: java sql hibernate jpa


【解决方案1】:

我建议使用生成的查询,并通过记录 hibernate 包或简单地将其添加到 hibernate.cfg.xml 来查看 hibernate 是如何转换为本机 Oracle 查询的:

<property name="show_sql">true</property>

也尝试添加 .otherData.idOtherData 以查看行为。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-28
    • 1970-01-01
    • 2016-09-21
    • 1970-01-01
    相关资源
    最近更新 更多