【问题标题】:jooq mysql select by <R extends Record> unique keys, with no regard to field namejooq mysql select by <R extends Record> 唯一键,不考虑字段名
【发布时间】:2017-02-14 02:39:41
【问题描述】:

我正在编写一个将记录插入或更新到 mysql 表中的方法,并且仅当字段“sample_time”大于表中当前记录的该值时才会更新。以下是我现在想做的事情。

 public <R extends Record> void upsertRecord(Table<R> table, R record) {
    Connection conn = getConnection();
    DSL.using(getConfiguration()).transaction(configuration -> {
        try (DSLContext dslContext = DSL.using(configuration)) {

            R old = // select with unique keys of table


            // something like if (old.get("update_time) < record.get("update_time"))
                dslContext.insertInto(table).set(record).onDuplicateKeyUpdate().set(record).execute();
                conn.commit();
           // }   
        } catch (SQLException e) {
            // TODO
        } finally {
            closeConnection(conn);
        }
    });
}

但我不知道如何通过记录的唯一键进行选择,而不考虑确切的字段名称或字段编号。所以我的问题是:

  1. 如何实现“按记录的唯一键选择而不考虑确切的字段名称或字段编号”
  2. 否则我如何在 jooq 中使用条件重复更新条件

提前感谢您的帮助!

【问题讨论】:

标签: java mysql jooq


【解决方案1】:

您可以通过Table.getPrimaryKey()获取对PrimaryKey元信息的引用:

UniqueKey<R> key = table.getPrimaryKey();
if (key != null) {
    List<TableField<R, ?>> fields = key.getFields();

    // Now create your condition from these fields
}

【讨论】:

  • 谢谢!它适用于单个主键,但似乎不适用于复合主键......我已经更新了问题中的代码。
  • @user3352035:我可以建议您恢复该编辑并提出一个新问题吗?很可能:1)您的新问题与您之前的问题并没有真正相关 2)如果您将我的答案复制到您的问题中,那么这个问题(和我的答案)对于将来访问这个问题的任何人来说都将变得不那么有用.
  • 你是对的,我已经回复了这个问题。感谢您的帮助! :)
  • @user3352035:太好了,谢谢。我会留意你的新问题并在那里回答
  • 没关系,我发现了我的错误,我错误地使用了 field(tf.getName()) 而不是 getValue(tf.getName()),正确的选择 sql 应该是:selectQuery .addConditions(tf.eq(record.getValue(tf.getName())));
猜你喜欢
  • 1970-01-01
  • 2013-05-20
  • 2011-01-01
  • 1970-01-01
  • 2020-12-23
  • 2012-06-04
  • 2015-04-18
  • 2020-03-22
  • 1970-01-01
相关资源
最近更新 更多