首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Hibernate 一對一唯一外鍵關聯註解配置詳解:以 Husband-Wife 為例

     編輯:程式設計綜合問答

表結構


Husband (husband_id PK, name)
Wife    (wife_id PK, name, husband_id FK UNIQUE)

業務規則:一個丈夫對應一個妻子,妻子表持有丈夫外鍵且唯一。

實體類註解

Husband 端(被引用方)


@Entity
@Table(name = "Husband")
public class Husband {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "husband_id")
    private Long id;

    private String name;

    @OneToOne(mappedBy = "husband", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private Wife wife; // 可選:雙向導航

    // getters/setters
}

Wife 端(外鍵持有方)


@Entity
@Table(name = "Wife",
    uniqueConstraints = @UniqueConstraint(columnNames = "husband_id")
)
public class Wife {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "wife_id")
    private Long id;

    private String name;

    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "husband_id", nullable = false, unique = true)
    private Husband husband;

    // getters/setters
}

關鍵註解解析

註解作用
@OneToOne聲明一對一關聯
@JoinColumn(name="husband_id", unique=true)指定外鍵列名,unique=true 生成唯一約束 (DDL)
mappedBy="husband"放在非持有方,表示由 Wife.husband 維護關聯
@UniqueConstraint(columnNames="husband_id")表級唯一約束,雙重保障
nullable=false外鍵非空,強制關聯

雙向關聯維護最佳實踐


public class Husband {
    // ...
    public void setWife(Wife wife) {
        if (wife == null) {
            if (this.wife != null) this.wife.setHusband(null);
        } else {
            wife.setHusband(this);
        }
        this.wife = wife;
    }
}

public class Wife {
    // ...
    public void setHusband(Husband husband) {
        this.husband = husband;
    }
}

統一由 Husband 端管理關聯,避免雙向同步混亂。

常見問題與解決

  1. 雙向無限遞歸序列化:Jackson 加 @JsonManagedReference / @JsonBackReference 或 @JsonIgnore。
  2. 延遲加載異常:事務外訪問 wife.husband,確保 @Transactional 範圍或用 fetch = FetchType.EAGER (慎用)。
  3. 外鍵列名不一致:@JoinColumn(name="husband_id", referencedColumnName="husband_id") 顯式指定。
  4. 共享主鍵策略:若 Wife 共享 Husband PK,改用 @MapsId + @OneToOne,不再需要 @JoinColumn。

DDL 驗證


CREATE TABLE Husband (
    husband_id BIGINT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(50)
);

CREATE TABLE Wife (
    wife_id BIGINT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(50),
    husband_id BIGINT NOT NULL UNIQUE,
    FOREIGN KEY (husband_id) REFERENCES Husband(husband_id)
);

參考資源

掌握 @JoinColumn(unique=true) + mappedBy 雙向配置,即可優雅實現一對一唯一外鍵關聯。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved