JPA unidirectional @OneToOne vs @ManyToOne with Hi

2020-07-18 11:06发布

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?

2条回答
够拽才男人
2楼-- · 2020-07-18 11:56

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.

查看更多
成全新的幸福
3楼-- · 2020-07-18 12:03

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.

查看更多
登录 后发表回答