在使用 MySQL Server 8.0.19 及更高版本时:可以为 集合 配置模式验证,以便在插入或更新之前根据模式验证 集合 中的文档。这是通过在 集合 创建或修改期间指定 JSON 模式 来完成的;然后,服务器在文档创建或更新时执行模式验证,如果文档未通过分配的模式验证,则返回错误。有关 MySQL 中 JSON 模式验证的更多信息,请参阅 JSON 模式验证函数。本节介绍如何使用 Connector/J 为 集合 配置模式验证。
要在创建 集合 期间配置模式验证,请将 CreateCollectionOptions 对象传递给 createCollection() 方法,该对象具有以下字段
reuse:由setReuseExisting方法设置的布尔值。如果为true,则当要创建的集合已存在于要包含它的模式中时,Connector/J 返回成功(不尝试将 JSON 模式应用于现有的集合);在相同情况下,如果参数设置为false,则 Connector/J 返回错误。如果未设置reuse,则将其视为false。-
validation:由setValidation()方法设置的Validation对象。Validation对象又包含以下字段-
level:由setLevel()方法设置的ValidationLevel类的枚举;它可以是以下两个值之一STRICT:严格验证。尝试插入或修改违反验证模式的文档会导致引发服务器错误。OFF:不验证。关闭模式验证。
如果未设置
level,则对于 MySQL Server 8.0.19,它将被视为OFF,对于 8.0.20 及更高版本,则为STRICT。 -
schema:表示 JSON 模式 的字符串,用于验证集合中的文档;由setSchema()方法设置。如果未提供
schema但level设置为 STRICT,则将根据默认模式{"type" : "object"}验证集合。
-
以下是配置 集合 创建时的模式验证的示例
Collection coll = this.schema.createCollection(collName,
new CreateCollectionOptions()
.setReuseExisting(false)
.setValidation(new Validation()
.setLevel(ValidationLevel.STRICT)
.setSchema(
"{\"id\": \"https://json-schema.fullstack.org.cn/geo\","
+ "\"$schema\": \"https://json-schema.fullstack.org.cn/draft-06/schema#\","
+ " \"description\": \"A geographical coordinate\","
+ " \"type\": \"object\","
+ " \"properties\": {"
+ " \"latitude\": {"
+ " \"type\": \"number\""
+ " },"
+ " \"longitude\": {"
+ " \"type\": \"number\""
+ " }"
+ " },"
+ " \"required\": [\"latitude\", \"longitude\"]"
+ " }"
)));
设置的字段可以通过相应的 getter 方法访问。
要修改 集合 的模式验证配置,请使用 modifyCollection() 方法,并将 ModifyCollectionOptions 对象传递给它,该对象具有与 CreateCollectionOptions 对象相同的字段,但 ModifyCollectionOptions 对象不存在 reuse 字段。对于 ModifyCollectionOptions 对象的 Validation 对象,用户可以设置其 level 或 schema,或两者都设置。以下是使用 modifyCollection() 更改模式验证配置的示例
schema.modifyCollection(collName,
new ModifyCollectionOptions()
.setValidation(new Validation()
.setLevel(ValidationLevel.OFF)
.setSchema(
"{\"id\": \"https://json-schema.fullstack.org.cn/geo\","
+ "\"$schema\": \"https://json-schema.fullstack.org.cn/draft-06/schema#\","
+ " \"description\": \"NEW geographical coordinate\","
+ " \"type\": \"object\","
+ " \"properties\": {"
+ " \"latitude\": {"
+ " \"type\": \"number\""
+ " },"
+ " \"longitude\": {"
+ " \"type\": \"number\""
+ " }"
+ " },"
+ " \"required\": [\"latitude\", \"longitude\"]"
+ " }"
)));
如果集合包含未根据通过 ModifyCollectionOptions 提供的新 JSON 模式验证的文档,则服务器将拒绝模式修改,并显示错误 错误 5180 (HY000) 文档根据分配给集合的模式无效。
createCollection() 和 modifyCollection() 已重载:可以在不分别传递 CreateCollectionOptions 或 ModifyCollectionOptions 的情况下调用它们,在这种情况下,不会将模式验证应用于 集合。