使用Spring定义Mongo Schema验证

Fed*_*tti 10 java spring mongodb spring-data-mongodb spring-boot

我想使用带有JSON Schema验证器选项的Spring-boot定义Mongo中Collection(https://docs.mongodb.com/manual/core/schema-validation/#json-schema),我不想要JSR -303 Bean验证(这不是一个有效的答案Spring数据mongoDb不是像Spring数据Jpa那样的空注释),但是在创建Collection时,定义了一个使用CollectionInfos()在JSON中显示的选项.

例如,如果我定义一个Account模型类,则喜欢:

public class Account {

@Id
private String id;

private String name;

private String surname;

@NotNull
private String username;
}
Run Code Online (Sandbox Code Playgroud)

我希望该集合使用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"
    }
}
]
Run Code Online (Sandbox Code Playgroud)

该过程可以类似于spring.jpa.hibernate.ddl-auto = create,因为它定义了模式级别的规则,而不是类似于Bean验证器,它定义了应用程序级别的规则.

Chr*_*obl 3

从版本开始,Spring Data MongoDB 支持 JsonSchema 2.1。详细信息请参阅参考文档。您可以使用如下所示的构建器来定义您的架构。

MongoJsonSchema schema = MongoJsonSchema.builder()
    .required("username")
    .properties(JsonSchemaProperty.string("username"))
    .build();

template.createCollection("account", CollectionOptions.empty().schema(schema));
Run Code Online (Sandbox Code Playgroud)

在编写 json 模式时,不支持从域类型创建。不过,您可能想加入DATAMONGO-1849 的讨论和/或尝试PR#733的快照。

该建议将通过调用类似的方法将 变成DomainTypeaMongoJsonSchemaMongoJsonSchema 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 
}
Run Code Online (Sandbox Code Playgroud)
{
    'type' : 'object',
    'required' : ['requiredCtorArg'],
    'properties' : {
        'requiredCtorArg' : { 'type' : 'string' },
        'nullableCtorArg' : { 'type' : 'string' },
        'optionalArg' : { 'type' : 'string' }
     }
}
Run Code Online (Sandbox Code Playgroud)