【问题标题】:jOOQ MySQL how to determine if complex DELETE affected row(s)jOOQ MySQL如何确定复杂的DELETE是否影响行
【发布时间】:2023-03-27 05:50:01
【问题描述】:

我正在尝试确定以下方法的结果,理想情况下将受影响的行数返回为Int

/**
 * Delete the Account ONLY if there are no `account_foo` or `account_bar` belonging to it.
 *
 * @param db        context.
 * @param accountId specific Account to delete.
 */
private void deleteAccount(DSLContext db, ULong accountId) throws DatabaseException {
  db.deleteFrom(ACCOUNT)
    .where(ACCOUNT.ID.eq(accountId))
    .andNotExists(
      db.selectFrom(ACCOUNT_FOO)
        .where(ACCOUNT_FOO.ACCOUNT_ID.eq(accountId))
    )
    .andNotExists(
      db.selectFrom(ACCOUNT_BAR)
        .where(ACCOUNT_BAR.ACCOUNT_ID.eq(accountId))
    )
    .execute();
}

以下查询在通过直接 MySQL 客户端执行时“有效”:

mysql> DELETE FROM `account` \
         WHERE `account`.`id`=12 \
           AND NOT EXISTS (SELECT `id` FROM `account_foo` WHERE `account_foo`.`account_id`=12) \
           AND NOT EXISTS (SELECT `id` FROM `account_bar` WHERE `account_bar`.`account_id`=12); \
       SELECT ROW_COUNT();
Query OK, 1 row affected (0.01 sec)

+-------------+
| ROW_COUNT() |
+-------------+
|           1 |
+-------------+
1 row in set (0.00 sec)

mysql> DELETE FROM `account` \
         WHERE `account`.`id`=14 \
           AND NOT EXISTS (SELECT `id` FROM `account_foo` WHERE `account_foo`.`account_id`=14) \
           AND NOT EXISTS (SELECT `id` FROM `account_bar` WHERE `account_bar`.`account_id`=14); \
       SELECT ROW_COUNT();
Query OK, 0 rows affected (0.00 sec)

+-------------+
| ROW_COUNT() |
+-------------+
|           0 |
+-------------+
1 row in set (0.00 sec)

但是以下版本实现 jOOQ 失败:

/**
 * Delete the Account ONLY if there are no `library` or `account_user_role` belonging to it.
 *
 * @param db        context.
 * @param accountId specific Account to delete.
 */
private Integer deleteAccount(DSLContext db, ULong accountId) throws DatabaseException {
  Integer rows;
  String accountIdString = accountId.toString();
  ResultSet rs = db.resultQuery(
    "DELETE FROM `account` "+
        "WHERE `account`.`id`=" + accountId.toString() +
        "AND NOT EXISTS (SELECT `id` FROM `account_foo` WHERE `account_foo`.`account_id`=" + accountId.toString() +") "+
        "AND NOT EXISTS (SELECT `id` FROM `account_bar` WHERE `account_bar`.`account_id`=" + accountId.toString() +"); "+
        "SELECT ROW_COUNT();"
  ).fetchResultSet();

  try {
    rs.next();
    rows = rs.getInt(1);
  } catch (SQLException e) {
    throw new DatabaseException("SQLException: " + e.getMessage());
  }

  return rows;
}

这是失败的堆栈跟踪:

org.jooq.exception.DataAccessException: SQL [DELETE FROM `account` WHERE `account`.`id`=14 AND NOT EXISTS (SELECT `id` FROM `account_foo` WHERE `account_foo`.`account_id`=14) AND NOT EXISTS (SELECT `id` FROM `account_bar` WHERE `account_bar`.`account_id`=14); SELECT ROW_COUNT();]; 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 'SELECT ROW_COUNT()' at line 1
    at org.jooq.impl.Tools.translate(Tools.java:1941)
    at org.jooq.impl.DefaultExecuteContext.sqlException(DefaultExecuteContext.java:659)
    at org.jooq.impl.AbstractQuery.execute(AbstractQuery.java:362)
    at org.jooq.impl.AbstractResultQuery.fetchLazy(AbstractResultQuery.java:365)
    at org.jooq.impl.AbstractResultQuery.fetchLazy(AbstractResultQuery.java:352)
    at org.jooq.impl.AbstractResultQuery.fetchResultSet(AbstractResultQuery.java:318)
    at io.outright.xj.hub.controller.account.AccountControllerImpl.deleteAccount(AccountControllerImpl.java:173)
    at io.outright.xj.hub.controller.account.AccountControllerImpl.deleteAccount(AccountControllerImpl.java:84)
    at io.outright.xj.hub.resource.accounts.AccountRecordResource.deleteAccount(AccountRecordResource.java:109)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:164)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:181)
    at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:158)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:101)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:389)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:347)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:102)
    at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:305)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
    at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:288)
    at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1110)
    at org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpContainer.service(GrizzlyHttpContainer.java:381)
    at org.glassfish.grizzly.http.server.HttpHandler$1.run(HttpHandler.java:219)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:565)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:545)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.sql.SQLSyntaxErrorException: 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 'SELECT ROW_COUNT()' at line 1
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:536)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:513)
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:115)
    at com.mysql.cj.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:1983)
    at com.mysql.cj.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1826)
    at com.mysql.cj.jdbc.PreparedStatement.execute(PreparedStatement.java:1153)
    at org.jooq.tools.jdbc.DefaultPreparedStatement.execute(DefaultPreparedStatement.java:194)
    at org.jooq.impl.AbstractResultQuery.execute(AbstractResultQuery.java:269)
    at org.jooq.impl.AbstractQuery.execute(AbstractQuery.java:348)
    ... 32 more

另请参阅:MySQL doc for ROW_COUNT()

【问题讨论】:

  • 你用的是什么 jOOQ 版本?
  • 3.8.6.感谢卢卡斯(感谢一切!)
  • 这可能是一个错误。以这种方式向 MySQL 发送批次时,我注意到了其他一些违规行为。对不起,这周我不能给你一个明确的答复。当我知道更多时会回到这个问题。
  • 感谢您的调查,以及早期的洞察力。

标签: java mysql orm jooq


【解决方案1】:

您遇到了两个问题:

1。您的 JDBC 驱动程序必须设置为允许每个 JDBC 语句进行多个查询

您需要将此标志添加到您的 JDBC 连接 URL:allowMultiQueries=true

See for instance this stack overflow question.

2。 jOOQ 只返回批处理的第一个结果

当通过 jOOQ 的普通 SQL API 发送批处理时,您只会从批处理中获得第一个结果。在这种情况下,这是 INSERT 语句的更新计数,而不是您的 SELECT 语句的结果(请注意,在 jOOQ 3.9.1 中还有错误 #5818)。

你可能想做的是使用ResultQuery.fetchMany()

db.resultQuery(
    "DELETE FROM `account` "+
    "WHERE `account`.`id`={0} "+
    "AND NOT EXISTS (SELECT `id` FROM `account_foo` WHERE `account_foo`.`account_id`={0}) "+
    "AND NOT EXISTS (SELECT `id` FROM `account_bar` WHERE `account_bar`.`account_id`={0}); "+
    "SELECT ROW_COUNT();", val(accountId)
  ).fetchMany();

这将返回更新计数和结果集。

注意,为了防止 SQL 注入风险,我还用绑定变量将您的 accountId 字符串连接替换为您的 SQL 语句。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-30
    • 2012-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-14
    • 1970-01-01
    相关资源
    最近更新 更多