我想使用 Spring-boot 和 JSON Schema validator 选项在 Mongo 中定义一个集合 ( https://docs.mongodb.com/manual/core/schema-validation/#json-schema ),我不想要 JSR-303 Bean 验证(这不是有效答案 Spring data mongoDb not null annotation like Spring data Jpa ),但在创建集合时定义一个选项,该选项使用 CollectionInfos() 显示在 JSON 中。
例如,如果我定义一个 Account 模型类,例如:
public class Account {
@Id
private String id;
private String name;
private String surname;
@NotNull
private String username;
}
我希望集合具有使用 db.getCollectionInfos() 的 json:
[
{
"name" : "account",
"type" : "collection",
"options" : {
"validator" : {
"$jsonSchema" : {
"bsonType" : "object",
"required" : [
"username"
]
}
}
},
"info" : {
"readOnly" : false,
"uuid" : UUID("979cdc4b-d6f3-4aef-bc89-3eee812773a5")
},
"idIndex" : {
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "databaseName.account"
}
}
]
该过程可能类似于 spring.jpa.hibernate.ddl-auto = create,因为它在模式级别定义规则,而不类似于在应用程序定义规则的 Bean validator 水平。
最佳答案
从版本 2.1
开始,Spring Data MongoDB 支持 JsonSchema。请参阅Reference Documentation了解详情。
您可以使用如下构建器来定义您的架构。
MongoJsonSchema schema = MongoJsonSchema.builder()
.required("username")
.properties(JsonSchemaProperty.string("username"))
.build();
template.createCollection("account", CollectionOptions.empty().schema(schema));
在撰写本文时,不支持从域类型创建 json 模式。 但是,您可能想加入讨论 DATAMONGO-1849和/或提供 PR#733 的快照一试。
建议通过调用类似 MongoJsonSchema schema = schemaCreator.createSchemaFor(DomainType.class);
将 DomainType
转换为 MongoJsonSchema
/p>
public class DomainType {
private final String requiredCtorArg;
private final @Nullable String nullableCtorArg;
private String optionalArg;
public DomainType(String requiredCtorArg, @Nullable String nullableCtorArg) {
this.requiredCtorArg = requiredCtorArg;
this.nullableCtorArg = nullableCtorArg;
}
// gettter / setter omitted
}
{
'type' : 'object',
'required' : ['requiredCtorArg'],
'properties' : {
'requiredCtorArg' : { 'type' : 'string' },
'nullableCtorArg' : { 'type' : 'string' },
'optionalArg' : { 'type' : 'string' }
}
}
关于java - 使用 Spring 定义 Mongo 模式验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50169457/