JPA unidirectional @OneToOne vs @ManyToOne with Hibernate - no difference?
Asked Answered
R

2

6

According to book Pro JPA 2 the main difference between unidirectional @ManyToOne and @OneToOne is that in @OneToOne:

Only one instance of the source entity can refer to the same target entity instance. In other words, the target entity instance is not shared among the source entity instances. In the database, this equates to having a uniqueness constraint on the source foreign key column (that is, the foreign key column in the source entity table).

The thing is, when I create such a mapping on entity and let Hibernate create schema, there is no unique constrain created at all. Why? Because of that for me, there is no difference between @ManyToOne and @OneToOne if I must explicitly define unique constraint for the mapping. I can do it for both of them and it makes no difference. Is that correct behaviour?

Rhyne answered 14/2, 2014 at 21:23 Comment(0)
A
8

There's no reason to use OneToOne if the association is a ManyToOne, and vice-versa. Use the appropriate annotation, which reflects the reality of the cardinality of the association. Not doing so would only confuse the developers of the app, if not Hibernate itself.

Whether the uniqueness of the source is constrained in the database or not doesn't change anything for Hibernate. In my experience, Hibernate does create the unique constraint in case of a OneToOne, and if it doesn't, then you should create it (I wouldn't use Hibernate to create the schema anyway, except for a quick 'n dirty demo app).

But of course, if there is a unique constraint, and you try to create two different entities with the same target entity, that will fail due to an error thrown by the database unique constraint.

Abed answered 14/2, 2014 at 21:35 Comment(2)
"Not doing so would only confuse the developers of the app" - this is the best reason I can think of! Can you specify version of Hibernate that creates constrain with @OneToOne?Rhyne
All the one I've recently used, IIRC. 3.6+. It might also depend on your database dialect.Abed
T
3

The important piece of the text is this equates to having a uniqueness constraint. It does not infer that the JPA provider will place the unique constraint on the two tables for you. It simply implies at the database level that a row in one table will only map to one row in another table.

There is a significant differences between a One to One and a One to Many, the cardinality of the relationship. Meaning in a One To Many relationship the entity on the one side of the relationship can be mapped (via the foreign key on the many side) to many entities on the many side of the relationship. In a One to One relationship the entities simply map to another lone entity.

Tarahtaran answered 14/2, 2014 at 21:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.