我有一个连接到存储文档的 MySQL 数据库的小型 Java 服务。每个文档都有一个名称,当复制一个文档时,新文档的名称为
<previous name> (#)
。文件表看起来像这样:
id | 姓名 |
---|---|
1 | 文件 |
2 | 文件(一) |
3 | 文件(2) |
4 | 另一份文件 |
5 | 另一个文件(一) |
我有一个有效的 MySQL 查询,它选择一个文档及其所有重复项,我正试图将其翻译成 jooq。
select * from documents
where name regexp '(TITLE_GOES_HERE|TITLE_GOES_HERE \\([:digit:]+\\))$';
-- For instance, to select rows 1, 2, and 3 of the above table,
-- I would replace `TITLE_GOES_HERE` with `A Document`, resulting
-- in the following MySQL query:
select * from documents
where name regexp '(A Document|A Document \\([:digit:]+\\))$';
注意: 如果您想要一个可用的正则表达式测试器,您可以在here 找到它。它与 MySQL 版本略有不同,但足以用于演示目的。
为了使这个查询以编程方式工作,我必须将正则表达式中的“TITLE_GOES_HERE”替换为我要查找的文档的名称。但是,这会在 jooq 中引发意外错误。
public List<Document> getOriginalAndDuplicates(String docName) {
SelectQuery<DocumentRecord> select = getDSLContext().selectQuery(DOCUMENT);
select.addCondition(
DSL.condition(
DSL.field(
// Binding for both the document AND the name
// Notice that the name binding is inside the regular expression
"{0} regexp '({1} \\\\([:digit:]+\\\\))'",
Boolean.class,
DOCUMENT.NAME,
docName)));
Result<DocumentRecord> records = select.fetch();
List<Document> docs = records.stream().map(documentConverter::convertTo).toList();
return docs;
}
当我运行它时,出现以下错误:
Caused by: org.jooq.exception.DataAccessException: SQL [select document.id, document.name from document where (document.name regexp '({1} \\([:digit:]+\\))')]; Syntax error in regular expression on line 1, character 2.
at org.jooq_3.14.16.MYSQL.debug(Unknown Source)
at org.jooq.impl.Tools.translate(Tools.java:2903)
at org.jooq.impl.DefaultExecuteContext.sqlException(DefaultExecuteContext.java:757)
at org.jooq.impl.AbstractQuery.execute(AbstractQuery.java:389)
... 27 common frames omitted
Caused by: java.sql.SQLException: Syntax error in regular expression on line 1, character 2.
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.ServerPreparedStatement.serverExecute(ServerPreparedStatement.java:555)
at com.mysql.cj.jdbc.ServerPreparedStatement.executeInternal(ServerPreparedStatement.java:339)
at com.mysql.cj.jdbc.ClientPreparedStatement.execute(ClientPreparedStatement.java:354)
at com.zaxxer.hikari.pool.ProxyPreparedStatement.execute(ProxyPreparedStatement.java:44)
at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.execute(HikariProxyPreparedStatement.java)
at org.jooq.tools.jdbc.DefaultPreparedStatement.execute(DefaultPreparedStatement.java:214)
at org.jooq.impl.Tools.executeStatementAndGetFirstResultSet(Tools.java:4217)
at org.jooq.impl.AbstractResultQuery.execute(AbstractResultQuery.java:283)
at org.jooq.impl.AbstractQuery.execute(AbstractQuery.java:375)
... 27 common frames omitted
发生错误是因为第一个绑定 (
{1}
) 没有被替换为文档名称。
有没有人遇到过这样的事情?
附加信息: 当我将
替换为硬编码值(例如{1}
)时,查询成功,没有任何问题。它只会在我尝试将A Document
绑定到变量值时引起问题。{1}