TL;DR:乍一看,架构可能看起来相同,但 OneToOne 可能有一个额外的UNIQUE INDEX
约束。这保证了One ToOne 关联。
关联映射的 Doctrine ORM 文档很好地说明了这一点(我不认为它特定于 Hibernate)。
一个例子:
多对一:
考虑这些表User
,Address
而列与该列User.address_id
具有 ManyToOne 关联Address.id
。这将是 SQL:
CREATE TABLE User (
id INT AUTO_INCREMENT NOT NULL,
address_id INT DEFAULT NULL,
PRIMARY KEY(id)
) ENGINE = InnoDB;
CREATE TABLE Address (
id INT AUTO_INCREMENT NOT NULL,
PRIMARY KEY(id)
) ENGINE = InnoDB;
ALTER TABLE User ADD FOREIGN KEY (address_id) REFERENCES Address(id);
一对一:
现在,考虑表Product
和Shipment
,而列与列Product.shipment_id
具有 OneToOne(单向)关联Shipment.id
。这将是 SQL:
CREATE TABLE Product (
id INT AUTO_INCREMENT NOT NULL,
shipment_id INT DEFAULT NULL,
UNIQUE INDEX UNIQ_6FBC94267FE4B2B (shipment_id),
PRIMARY KEY(id)
) ENGINE = InnoDB;
CREATE TABLE Shipment (
id INT AUTO_INCREMENT NOT NULL,
PRIMARY KEY(id)
) ENGINE = InnoDB;
ALTER TABLE Product ADD FOREIGN KEY (shipment_id) REFERENCES Shipment(id);
唯一的区别是UNIQUE INDEX
指示表中不能shipment.id
出现两次的指令Product
。这保证了One ToOne 关联。