删除查询

执行删除行的查询。

int rows = new QContact()
  .name.equalTo("[email protected]")
  .delete();
delete from contact where email = ?
示例 2
int rows = new QContact()
  .email.startsWith("rob")
  .firstName.eq("Rob")
  .delete();
delete from contact where email like ? escape'|'  and first_name = ?
示例 3

当 where 表达式位于关联 Bean 路径(如 OneToMany)上时,SQL 删除将使用子查询。

int rows = new QCustomer()
  .contacts.email.contains("foo.com")
  .delete();
delete from customer where id in (
  select distinct t0.id
  from customer t0
  join contact u1 on u1.customer_id = t0.id
  where u1.email like ? escape'|'
)

级联删除

如果我们正在删除的 Bean 类型已通过例如 @ManyToOne(cascade=CascadeType.ALL) 定义了级联删除,那么将执行级联。

示例

在以下示例中,Customer 将保存和删除级联到 billingAddress。

// setup - a customer with a billing address
Customer customer = new Customer("Bad Example");
customer.setBillingAddress(new Address("My Street", "Hopeful City"));
customer.save();


// deleting customer needs to cascade delete the billingAddress
int rows = new QCustomer()
.name.startsWith("Bad")
.delete();

上述操作最终将在事务中执行 4 条语句。

-- first select the ids of customers that will be deleted
select t0.id from customer t0 where t0.name like ? escape'' ; --bind(Bad%)

-- select the foreign keys that will be cascade deleted
select t0.id, t0.billing_address_id, t0.shipping_address_id from customer t0 where t0.id in (? )

-- delete the customers
delete from customer where id=?;

-- [cascade] delete the related billing addresses
delete from address where id=?;

persistCascade false

当事务已关闭 persist 级联时,查询将改为仅执行单条删除语句。

try (Transaction transaction = DB.beginTransaction()) {

  // turn off persist cascade
  transaction.setPersistCascade(false);

  int deletedRows =
    new QCustomer()
      .name.startsWith("Bad")
      .delete();

  transaction.commit();
}
delete from customer where name like ? escape'' ; --bind(Bad%)

比较 SqlUpdate

如果我们想要直接使用 SQL,我们可以改为使用 SqlUpdate 来执行 sql delete 语句。