【问题标题】:JOOQ: fetch single row by primary key?JOOQ:按主键获取单行?
【发布时间】:2019-05-17 15:23:48
【问题描述】:

我有一个主键值,我想获取一条记录进行更新,所以我现在写:

AccountRecord account = db.selectFrom(ACCOUNT).
  where(ACCOUNT.ID.eq(identity.getAccountId())).fetchSingle();

JOOQ 知道我的表的主键(例如它生成 onKey() 方法等) - 所以我希望得到类似的东西:

AccountRecord account = db.fetchByKey(ACCOUNT, identity.getAccountId())

但这似乎不是一回事。 有没有更简洁的方式使用 JOOQ API 来做我想做的事?

【问题讨论】:

    标签: java sql jooq


    【解决方案1】:

    你可以使用DSLContext.fetchSingle(Table, Condition):

    AccountRecord account = db.fetchSingle(ACCOUNT, ACCOUNT.ID.eq(identity.getAccountId()));
    

    生成的ACCOUNT 引用没有对键类型的类型引用,因此您建议的语法是不可能的。您当然可以extend the code generator 生成一个方法,该方法采用主键值并生成Condition

    class Account {
        ..
        public Condition byKey(Long accountId) {
            return ID.eq(accountId);
        }
        public AccountRecord fetchByKey(DSLContext ctx, Long accountId) {
            return ctx.fetchSingle(this, byKey(accountId));
        }
    }
    

    现在使用上面的:

    AccountRecord account = ACCOUNT.fetchByKey(db, identity.getAccountId());
    

    【讨论】:

      猜你喜欢
      • 2021-01-30
      • 2014-04-16
      • 2019-11-03
      • 1970-01-01
      • 1970-01-01
      • 2013-08-25
      • 1970-01-01
      • 1970-01-01
      • 2020-07-06
      相关资源
      最近更新 更多