I annotated my fields with only @OneToOne and when I check the database (generated using liquibase) saw that there are unique constraints on database columns.
Does this mean @OneToOne implies uniqueness just by itself, eg. one Building can only be in one city, and no other Buildings can be in the same city?
What do I do when I want to tell that there may be other other buildings in the same city?
I don't want to put a Buildings field in the city class, because I wouldn't ever call city.getBuildings();. Does any of the below require a bidirectional reference?
class Building {
@OneToOne(optional = false)
City city;
}
class Building {
@OneToOne(optional = false)
@JoinColumn(unique = false)
City city;
}
class Building {
@JoinColumn(unique = true)
City city;
}
class Building {
@ManyToOne
City city;
}
The JPA specification says that for a bidirectional OneToOne relationship (2.10.1 Bidirectional OneToOne Relationships):
Assuming that:
- Entity A references a single instance of Entity B.
- Entity B references a single instance of Entity A.
- Entity A is specified as the owner of the relationship.
The following mapping defaults apply:
- Entity A is mapped to a table named A.
- Entity B is mapped to a table named B.
- Table A contains a foreign key to table B. [...] The foreign key column has the same type as the primary key of table B and there is a unique key constraint on it.
In case of unidirectional OneToOne relationship (2.10.3.1 Unidirectional OneToOne Relationships):
The following mapping defaults apply:
- Entity A is mapped to a table named A.
- Entity B is mapped to a table named B.
- Table A contains a foreign key to table B. [...] The foreign key column has the same type as the primary key of table B and there is a unique key constraint on it.
If you have a City-Building relationship, then for any reasonable city it would be a OneToMany/ManyToOne relationship, since a given city can have multiple buildings, but a given building can be only in one city.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With