當使用 MySQL Server 8.0.19 及更新版本時:可以為 Collection 設定結構描述驗證,以便在插入或更新 Collection 中的文件之前,根據結構描述驗證這些文件。這是透過在 Collection 建立或修改期間指定 JSON 結構描述 來完成的;然後,伺服器會在文件建立或更新時執行結構描述驗證,如果文件未根據指派的結構描述進行驗證,則會傳回錯誤。如需 MySQL 中 JSON 結構描述驗證的詳細資訊,請參閱JSON 結構描述驗證函式。本節說明如何使用 Connector/J 為 Collection 設定結構描述驗證。
若要在建立 Collection 期間設定結構描述驗證,請將 CreateCollectionOptions 物件傳遞至 createCollection() 方法,此物件具有下列欄位
reuse:由setReuseExisting方法設定的布林值。如果它是true,當要建立的Collection已存在於要包含它的Schema中時,Connector/J 會傳回成功 (而不會嘗試將 JSON 結構描述套用至現有的Collection);在相同情況下,如果參數設定為false,則 Connector/J 會傳回錯誤。如果未設定reuse,則會將其視為false。-
validation:由setValidation()方法設定的Validation物件。Validation物件反過來包含以下欄位-
level:ValidationLevel類別的列舉,由setLevel()方法設定;它可以是以下兩個值之一STRICT:嚴格驗證。嘗試插入或修改違反驗證結構描述的文件會導致引發伺服器錯誤。OFF:無驗證。結構描述驗證已關閉。
如果未設定
level,則對於 MySQL Server 8.0.19 會將其視為OFF,對於 8.0.20 及更新版本會將其視為STRICT。 -
schema:代表 JSON 結構描述 的字串,用於驗證Collection中的Document;由setSchema()方法設定。如果未提供
schema但level設定為 STRICT,則會根據預設結構描述{"type" : "object"}驗證Collection。
-
以下是如何在建立 Collection 時設定結構描述驗證的範例
Collection coll = this.schema.createCollection(collName,
new CreateCollectionOptions()
.setReuseExisting(false)
.setValidation(new Validation()
.setLevel(ValidationLevel.STRICT)
.setSchema(
"{\"id\": \"http://json-schema.org/geo\","
+ "\"$schema\": \"http://json-schema.org/draft-06/schema#\","
+ " \"description\": \"A geographical coordinate\","
+ " \"type\": \"object\","
+ " \"properties\": {"
+ " \"latitude\": {"
+ " \"type\": \"number\""
+ " },"
+ " \"longitude\": {"
+ " \"type\": \"number\""
+ " }"
+ " },"
+ " \"required\": [\"latitude\", \"longitude\"]"
+ " }"
)));
設定的欄位可透過對應的 getter 方法存取。
若要修改 Collection 的結構描述驗證設定,請使用 modifyCollection() 方法,並將 ModifyCollectionOptions 物件傳遞給它,此物件具有與 CreateCollectionOptions 物件相同的欄位,但 reuse 欄位除外,ModifyCollectionOptions 物件不存在此欄位。對於 ModifyCollectionOptions 物件的 Validation 物件,使用者可以設定其 level 或 schema,或兩者都設定。以下是使用 modifyCollection() 變更結構描述驗證設定的範例
schema.modifyCollection(collName,
new ModifyCollectionOptions()
.setValidation(new Validation()
.setLevel(ValidationLevel.OFF)
.setSchema(
"{\"id\": \"http://json-schema.org/geo\","
+ "\"$schema\": \"http://json-schema.org/draft-06/schema#\","
+ " \"description\": \"NEW geographical coordinate\","
+ " \"type\": \"object\","
+ " \"properties\": {"
+ " \"latitude\": {"
+ " \"type\": \"number\""
+ " },"
+ " \"longitude\": {"
+ " \"type\": \"number\""
+ " }"
+ " },"
+ " \"required\": [\"latitude\", \"longitude\"]"
+ " }"
)));
如果 Collection 包含未根據透過 ModifyCollectionOptions 提供的新的 JSON 結構描述進行驗證的文件,則伺服器將會拒絕結構描述修改,並顯示錯誤 ERROR 5180 (HY000) Document is not valid according to the schema assigned to collection。
createCollection() 和 modifyCollection() 是多載的:可以在不將 CreateCollectionOptions 或 ModifyCollectionOptions 分別傳遞給它們的情況下呼叫它們,在這種情況下,結構描述驗證將不會套用至 Collection。