領先一步
VMware 提供培訓和認證,加速您的進步。
瞭解更多作為 Spring Data 釋出火車 Codd 的第一個里程碑版本已經發布一段時間了,我想重點介紹一下 MongoDB 模組中附帶的一些新特性。
有時,在 MongoDB 聚合框架的投影中定義算術表示式會相當複雜。
假設訂單聚合的一部分是其總價,該價格使用以下公式有效計算:(netPrice * discountRate + fixedCharge) * taxRate
。如果折扣率為 0.8,固定費用為 1.2,稅率為 1.19,則使用 MongoDB 聚合框架編碼此公式的相應 DBObject
如下所示
{ "aggregate": "product",
"pipeline": [
{ "$project": {
"name": 1,
"netPrice": 1,
"grossPrice": {
"$multiply": [
{ "$add": [ { "$multiply" : [ "$netPrice", 0.8 ] }, 1.2 ] }, 1.19
]
}
}
}
]
}
藉助我們對將 SpEL 表示式轉換為適當的 MongoDB 投影表示式的新支援,這變得容易得多,因為您可以有效地直接使用原始公式
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 聚合框架表示式。請注意,我們使用陣列索引運算子引用了先前宣告的變數,該運算子指向可變引數 Object 陣列,….andExpression(…)
將其作為第二個引數。您可以在 SpelExpressionTransformer
的單元測試中找到更多使用示例。
在此版本中,我們攻克了 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。
CrudRepository
中定義的方法通常由特定於儲存的類實現,該類提供所需的行為。但是,您可能希望透過簡單的查詢執行來覆蓋這些方法的執行。現在,您可以使用 @Query
註解標註任何 CRUD 方法來定義應執行的查詢表示式。對於基於 MongoDB 的儲存庫,它看起來如下所示
interface PersonRepository extends MongoRepository<Person, String> {
@Query("{ 'username' : { $nin : [ 'admin' ] }}")
List<Person> findAll();
}
此機制適用於所有支援儲存庫抽象的模組。
到目前為止,繫結到 MongoDB DBRef 的域模型屬性是急切載入的,如果您在實體之間存在雙向 DBRef 關係,這會導致一些問題。現在,您可以在 @DBRef
註解上設定一個 lazy
屬性,以宣告一個欄位將按需(惰性)解析。當載入文件時,如果檢測到此類欄位,我們將為給定物件生成一個代理,並在呼叫物件的任何方法時(除了來自 java.lang.Object
的方法)解析它。
class User{
@DBRef(lazy = true) List<User> fans;
// …
}
本文簡要概述了最新 Codd 版本中的一些新特性,但還有更多內容等待您去探索,您可以在我們的精選更新日誌中看到更多資訊。
請參閱Spring Data MongoDB 專案頁面獲取更多資訊以及下載、文件等的連結。我們希望使用者能夠試用此里程碑版本。