我想使用带有JSON Schema验证器选项(https://docs.mongodb.com/manual/core/schema-validation/#json-schema)的Spring-boot在Mongo中定义一个Collection,我不想要JSR-303 Bean验证(这不是一个有效的答案Spring data mongoDb not null annotation like Spring data Jpa),而是定义,在此刻Collection的创建,使用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验证器,它定义了应用程序级别的规则。
从版本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的快照。
这个建议会把DomainType
变成一个MongoJsonSchema
,叫做像MongoJsonSchema schema = schemaCreator.createSchemaFor(DomainType.class);
这样的东西
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' }
}
}