如何在不设置值和 return 新创建的 ID 的情况下插入()?

How to insertInto() without setting values and return the newly created ID?

如何在不指定任何值和 return 新创建的 ID 的情况下插入记录?如果我这样做:

private Long createOffer() {

    return this.ctx.insertInto(StoreOffer.STORE_OFFER, StoreOffer.Store_OFFER.ID)
            .returning(StoreOffer.STORE_OFFER.ID)
            .fetchOne().getValue(StoreOffer.STORE_OFFER.ID);
}

我收到 java.lang.NullPointerException。如果我只是将它设置为 null Not-Null-Constraint 就会被触发..

private Long createOffer() {

    return this.ctx.insertInto(StoreOffer.STORE_OFFER, StoreOffer.Store_OFFER.ID)
            .values((Long)null)
            .returning(StoreOffer.STORE_OFFER.ID)
            .fetchOne().getValue(StoreOffer.STORE_OFFER.ID);
}

我也试过这个:

private Long createOffer() {
    StoreOfferRecord storeOfferRecord = this.ctx.newRecord(StoreOffer.STORE_OFFER);
    storeOfferRecord.store();
    return storeOfferRecord.getId();
}

但 ID 始终是 null


table store_offer 目前看起来像这样:

CREATE TABLE store_offer (

    -- PRIMARY KEY

    id BIGSERIAL PRIMARY KEY
);

您可以尝试 new Long(0) 而不是 (Long)null

使用INSERT INTO .. DEFAULT VALUES

jOOQ 支持 SQL 标准 DEFAULT VALUES 子句 INSERT 语句 use-case:

return this.ctx.insertInto(StoreOffer.STORE_OFFER)
               .defaultValues()
               .returning(StoreOffer.STORE_OFFER.ID)
               .fetchOne().getValue(StoreOffer.STORE_OFFER.ID);

另请参阅: http://www.jooq.org/doc/latest/manual/sql-building/sql-statements/insert-statement/insert-default-values/

为什么你有 NullPointerException

您能够编写以下查询 because of an API flaw (#3771)。以下甚至不应该编译:

return this.ctx.insertInto(StoreOffer.STORE_OFFER, StoreOffer.Store_OFFER.ID)
               .returning(StoreOffer.STORE_OFFER.ID)
               .fetchOne().getValue(StoreOffer.STORE_OFFER.ID);

为什么 record.store() 不起作用:

jOOQ 记录有一个内部 per-column 更改标志。没有 record-level changed 标志指示整个记录需要发送到数据库,即使没有任何更改。具体来说,如果需要发布 UPDATE 声明,这将没有任何意义。