这种获取可以更“优雅”地完成吗?

时间:2016-01-08 19:44:37

标签: java sql jooq

我正在使用jOOQ,我不太确定我是否按照我应该的方式使用它。我想知道下面的代码是否可以写得更优雅。通过“优雅地”我的意思是基本上改变关于列的任何是非常烦人的。如果我添加,删除或更改列的顺序,我必须更改所有结果和Table<>对象等。我很确定我将来会遇到类似下面的请求,因此我想知道我是否可以简化这一点。

此外,我注意到on.fetch()和类似的结果是Result<Record6<..>>。我看了那些RecordX课程。其中有22个。我认为我不会需要那个,但如果我想读23列呢?

public List<StoreItemDTO> getItems(Long storeId) {

  // Get all item_ids for the store

  SelectConditionStep<Record1<Long>> where = this.ctx
    .select(STORE_ITEM.ID)
    .from(STORE_ITEM)
    .where(STORE_ITEM.STORE_ID.eq(storeId));

  // Get all store_item_details (all languages) according to the fetched item_ids

  Table<Record5<Long, Long, String, String, Long>> storeItemDetails = this.ctx
    .select(
        STORE_ITEM_DETAILS.ID,
        STORE_ITEM_DETAILS.STORE_ITEM_ID,
        STORE_ITEM_DETAILS.NAME,
        STORE_ITEM_DETAILS.DESCRIPTION,
        STORE_ITEM_DETAILS.STORE_LANGUAGE_ID
        )
    .from(STORE_ITEM_DETAILS)
    .where(STORE_ITEM_DETAILS.STORE_ITEM_ID.in(where))
    .asTable("storeItemDetails");

  // Join the result and get the items for the store in all languages

  SelectOnConditionStep<Record6<Long, Long, Long, String, String, Long>> on = this.ctx
    .select(
        STORE_ITEM.ID, 
        STORE_ITEM.STORE_ID,
        storeItemDetails.field(STORE_ITEM_DETAILS.ID),
        storeItemDetails.field(STORE_ITEM_DETAILS.NAME),
        storeItemDetails.field(STORE_ITEM_DETAILS.DESCRIPTION),
        storeItemDetails.field(STORE_ITEM_DETAILS.STORE_LANGUAGE_ID)          
        )
    .from(STORE_ITEM)
    .join(storeItemDetails)
    .on(storeItemDetails.field(STORE_ITEM_DETAILS.STORE_ITEM_ID).eq(STORE_ITEM.ID));

  Result<Record6<Long, Long, Long, String, String, Long>> fetch = on.fetch();

  // ..

  return null;
}

1 个答案:

答案 0 :(得分:2)

如果您不需要类型安全,请不要使用它。例如。以下工作也很好

// Get all item_ids for the store
SelectConditionStep<?> where = this.ctx...

// Get all store_item_details (all languages) according to the fetched item_ids
Table<?> storeItemDetails = this.ctx...

// Join the result and get the items for the store in all languages
SelectOnConditionStep<Record6<Long, Long, Long, String, String, Long>> on = this.ctx...

扩展类型安全性对于编译器来说非常好,因为它可以执行类型推断,例如:当你写作时:

  • UNIONŠ
  • IN谓词
  • 将结果提取到lambda表达式时

您可能正在编写所有这些类型,因为您正在使用IDE自动完成,并且您的IDE首先会提出最具体的建议。但是在上面的例子中使用通配符也可以正常工作,例如:

Result<?> fetch = this.ctx 
                     // .. 
                     .fetch();

for(Record record : fetch) {            
    String value = record.getValue(STORE_ITEM_DETAILS.NAME);            
    System.out.println(value);
}
  

我不认为我曾经需要那个,但如果我想读23列怎么办?

没有什么重大变化。另见手册: http://www.jooq.org/doc/latest/manual/sql-execution/fetching/record-n

您仍然可以选择是否使用显式记录输入(记录中没有度数):

Result<Record> result = query.fetch();

...或者您是否使用通配符:

Result<?> result = query.fetch();
相关问题