TL;DR: The schema might look the same at first glance, but the OneToOne may have an additional UNIQUE INDEX
constraint. This guarantees the OneToOne association.
This is nicely illustrated by the Doctrine ORM documentation of Association Mapping (I don't think it's specific to Hibernate).
An example:
ManyToOne:
Consider the tables User
and Address
while the column User.address_id
has a ManyToOne association to the Address.id
column. This would be the 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);
OneToOne:
Now, consider the tables Product
and Shipment
, while the column Product.shipment_id
has a OneToOne (unidirectional) association to the Shipment.id
column. This would be the 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);
The only difference is the UNIQUE INDEX
directive which dictates there must not be a shipment.id
occuring twice in the Product
table. This guarantees the OneToOne association.