Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does @OneToOne imply uniqueness?

Tags:

jpa

liquibase

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?

  • add @JoinColumn(unique = false),
  • only use @JoinColumn(unique = false) without @oneToOne,
  • or use @ManyToOne?
  • or leave it without any annotations?

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;
}
like image 610
uylmz Avatar asked Oct 31 '25 20:10

uylmz


1 Answers

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.

like image 112
Adam Michalik Avatar answered Nov 03 '25 12:11

Adam Michalik