Spring Data MongoDB 1.4 M1 的新功能

工程 | Thomas Darimont | 2013年12月04日 | ...

由於 Spring Data Release Train Codd 的第一個里程碑現在已經稍微冷卻下來,我想重點介紹 MongoDB 模組隨附的一些新功能。

Aggregation Framework 中投影的 SpEL 支援

有時候,在 MongoDB aggregation framework 投影中定義算術運算式可能會非常複雜。

假設訂單的 aggregation 的一部分是其總價,實際上是使用以下公式計算的:(netPrice * discountRate + fixedCharge) * taxRate。如果折扣率為 0.8,固定費用為 1.2,稅率為 1.19,則使用 MongoDB aggregation framework 對此公式進行編碼的相應 DBObject 如下

{ "aggregate": "product",
  "pipeline": [
    { "$project": {
        "name": 1,
        "netPrice": 1,
        "grossPrice": {
          "$multiply": [ 
            { "$add": [ { "$multiply" : [ "$netPrice", 0.8 ] }, 1.2 ] }, 1.19
          ]
        }
      }
    }
  ]
}

由於我們新增了在適當的 MongoDB 投影運算式中轉換 SpEL 運算式的支援,這變得容易得多,因為您可以有效地按原樣使用原始公式

import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;
 
double discountRate = 0.8;
double fixedCharge = 1.2;
double taxRate = 1.19;
 
TypedAggregation<Product> agg = newAggregation(Product.class,
  project("name", "netPrice")
    .andExpression("(netPrice * [0]  + [1]) * [2]", 
      discountRate, fixedCharge, taxRate)
    .as("grossPrice")
);
 
AggregationResults<DBObject> result = mongoTemplate.aggregate(agg, DBObject.class);
List<DBObject> resultList = result.getMappedResults();

在幕後,我們會將 SpEL 運算式的已解析 AST (抽象語法樹) 轉換為適當的 MongoDB aggregation framework 運算式。請注意,我們透過使用陣列索引運算子來引用先前宣告的變數,該運算子引用 varargs Object 陣列,….andExpression(…) 作為第二個參數。您可以在 SpelExpressionTransformer單元測試中找到其他使用範例。

使用 Java Config 進行稽核配置

在此版本中,我們征服了 Spring Data 模組的最後一個需要嚴格 XML 配置的功能 - 稽核。如果您想在應用程式中使用稽核,您現在要做的就是使用新的 @EnableMongoAuditing 註釋(或 JPA 的等效註釋)

@Configuration
@EnableMongoAuditing
@EnableMongoRepositories
class Config {
 
  @Bean
  public MongoOperations mongoTemplate() throws Exception {
    MongoClient client = new MongoClient();
    return new MongoTemplate(new SimpleMongoDbFactory(client, "database"));
  }

  @Bean
  public MongoMappingContext mappingContext() {
    return new MongoMappingContext();
  }

  @Bean
  public AuditorAware<BusinessEntity> auditorProvider() {
    return new MongoAuditorProvider<BusinessEntity>();
  }
}

透過 @EnableMongoAuditing 啟用的基礎結構將自動擷取 ApplicationContext 中可用的 AuditorAware 實例。如果您只想在實體上設定建立和修改日期,則無需宣告 AuditorAware Bean。

重新定義 CRUD 方法的行為

CrudRepository 中定義的方法通常由提供必要行為的儲存專用類別實作。但是,您可能希望透過簡單的查詢執行來覆寫這些方法的執行。您現在可以使用 @Query 註釋來註釋任何 CRUD 方法,以定義應執行的查詢運算式。對於基於 MongoDB 的儲存庫,它看起來如下

interface PersonRepository extends MongoRepository<Person, String> {

  @Query("{ 'username' : { $nin : [ 'admin' ] }}")
  List<Person> findAll();
}

此機制適用於所有支援儲存庫抽象的模組。

支援延遲 DBRef

到目前為止,您的網域模型中繫結到 MongoDB DBRef 的屬性都是以急切方式載入的,如果您在實體之間具有雙向 DBRef 關係,這會造成一些麻煩。您現在可以在 @DBRef 註釋上設定 lazy 屬性,以宣告欄位要延遲解析。當我們在載入文件時偵測到此類欄位時,我們會為給定的物件產生一個 Proxy,並在呼叫物件的任何方法時解析它(預期來自 java.lang.Object 的方法)。

class User{
    
  @DBRef(lazy = true) List<User> fans;
  // …
}

結論

這結束了對最新 Codd 版本中一些新功能的簡要概述,但還有更多內容有待發現,您可以在我們精心策劃的變更日誌中看到。

請參閱Spring Data MongoDB 專案頁面,以取得更多資訊以及下載、文件等的連結。我們非常感謝使用者試用此里程碑。

取得 Spring 電子報

隨時掌握 Spring 電子報

訂閱

領先一步

VMware 提供培訓和認證,以加速您的進度。

了解更多

取得支援

Tanzu Spring 在一個簡單的訂閱中提供 OpenJDK™、Spring 和 Apache Tomcat® 的支援和二進位檔案。

了解更多

即將舉行的活動

查看 Spring 社群中所有即將舉行的活動。

查看全部