我有一個 PostgresQL 資料庫,我以編程方式在我的 Java 應用程式代碼中填充它。有一個“訊息”表 - 它存盤來自郵件服務的傳入訊息。還有“電話”——存盤電話號碼。每個物體的 UUID 是自動生成的。問題是如果訊息可以包含相同的數字。而在資料庫中,由于自動生成,phone_id 總是不同的(見圖)。如何避免這種情況?
uj5u.com熱心網友回復:
雖然這個答案與規范化無關,但我希望它有所幫助。如果您想將 UUID 號碼鏈接到電話號碼,您還可以生成 UUID v3 或 UUID v5 而不是 UUIDv4。UUIDv4 是隨機的,而 UUID v3/v5 對于相同的輸入總是相同的。
要生成 UUIDv3:
package com.example;
import java.util.UUID;
public class Example {
public static void main(String[] args) {
String string1 = "89207143040";
String string2 = "8 920 714 30 40";
String string3 = " 8 920 714-30-40";
// Remove all non numeric chars from the phone number and generate a UUIDs v3.
UUID uuid1 = UUID.nameUUIDFromBytes(string1.replaceAll("[^\\d.]", "").getBytes());
UUID uuid2 = UUID.nameUUIDFromBytes(string2.replaceAll("[^\\d.]", "").getBytes());
UUID uuid3 = UUID.nameUUIDFromBytes(string3.replaceAll("[^\\d.]", "").getBytes());
System.out.println(uuid1 " -> " string1);
System.out.println(uuid2 " -> " string2);
System.out.println(uuid3 " -> " string3);
}
}
輸出:
84345d67-45a8-365e-8da7-5d5c90c1ce0c -> 89207143040
84345d67-45a8-365e-8da7-5d5c90c1ce0c -> 8 920 714 30 40
84345d67-45a8-365e-8da7-5d5c90c1ce0c -> 8 920 714-30-40
uj5u.com熱心網友回復:
一種做法是在phone_id欄位上使用約束來避免具有相同的重復物體phone_number。
如果您使用獨立于資料庫的庫來管理像Liquibase這樣的資料庫,您可以通過
<changeSet author="liquibase-docs" id="dropUniqueConstraint-example">
<dropUniqueConstraint catalogName="cat"
constraintName="const_name"
schemaName="your schma name"
tableName="Message"
uniqueColumns="phone_number"/>
或直接在資料庫中使用
ALTER TABLE Message ADD CONSTRAINT constraint_name UNIQUE (phone_number);
滿足2NF的另一種方法是創建備用表,其中外鍵指向Message表中的 phome_number 具有One to Many 關聯或者Many to Many如果它們具有雙向關系。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/454157.html
標籤:爪哇 春天 PostgreSQL jpa 开机
