領先一步
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聚合框架表示式。請注意,我們透過使用陣列索引運算子引用了先前宣告的變數,該運算子引用了….andExpression(…)作為第二個引數的varargs物件陣列。您可以在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專案頁面以獲取更多資訊以及下載、文件等的連結。我們非常感謝使用者試用這個里程碑版本。