首页 > 解决方案 > JOOQ - 更新新添加的列

问题描述

我正在使用 JOOQ 和 Postgresql 数据库,我正在尝试将新列添加到表中,然后使用值更新这些列。这些值对应于推文的情绪。

到目前为止,我的尝试(没有编译错误的那个:)是:

final String SENTIMENT_NEGATIVE = "sentiment_negative";
final String SENTIMENT_NEUTRAL  = "sentiment_neutral";
final String SENTIMENT_POSITIVE = "sentiment_positive";
final String SENTIMENT_COMPOUND = "sentiment_compound";

context.alterTable(Tweets.TWEETS).addColumnIfNotExists(SENTIMENT_NEGATIVE, DOUBLE).execute();
context.alterTable(Tweets.TWEETS).addColumnIfNotExists(SENTIMENT_NEUTRAL , DOUBLE).execute();
context.alterTable(Tweets.TWEETS).addColumnIfNotExists(SENTIMENT_POSITIVE, DOUBLE).execute();
context.alterTable(Tweets.TWEETS).addColumnIfNotExists(SENTIMENT_COMPOUND, DOUBLE).execute();

// example usage
for (Record record: tweetsResult) {
    String tweet = record.get(Tweets.TWEETS.CONTENT);
    SentimentAnalyzer sentimentAnalyzer = new SentimentAnalyzer(tweet);
    sentimentAnalyzer.analyze();
    log.debug(sentimentAnalyzer.getPolarity() + " | " + tweet);

    context.update(Tweets.TWEETS)
        .set(
            row(SENTIMENT_NEGATIVE,
               SENTIMENT_NEUTRAL,
               SENTIMENT_POSITIVE,
               SENTIMENT_COMPOUND),
            row(getPolarity(sentimentAnalyzer, SENTIMENT_NEGATIVE),
                getPolarity(sentimentAnalyzer, SENTIMENT_NEUTRAL),
                getPolarity(sentimentAnalyzer, SENTIMENT_POSITIVE),
                getPolarity(sentimentAnalyzer, SENTIMENT_COMPOUND))
            )
        .where(Tweets.TWEETS.ID.eq(record.get(Tweets.TWEETS.ID)))
        .execute();
}

但我收到一个错误:

线程“主”org.jooq.exception.DataAccessException 中的异常:SQL [更新“公共”。“推文”设置(?,?,?,?)=行(?,?,?,?)其中“公共”。 "推文"."id" = ?]; 错误:“$1”处或附近的语法错误

我知道我可以根据 db 模式的变化重新生成我的源代码,但我想知道是否可以使用我的方法来做到这一点。

标签: postgresqlsql-updatejooq

解决方案


理想情况下,您将实现查询逻辑和迁移逻辑的更清晰的分离。FlywayLiquibase等数据库更改管理工具将帮助您维护架构,并在应用程序启动时应用增量。

一旦你使用了数据库变更管理软件,你也可以在你的开发过程中使用它,例如通过将你的增量一直应用到测试容器中的开发数据库,​​然后你可以从中重新生成你的代码,请参阅

这样,您生成的代码始终是最新的,并且您不必求助于使用String最新列的临时类型不安全表示。


推荐阅读