JPA单向@OneToOne vs @ManyToOne与Hibernate - 没有区别? [英] JPA unidirectional @OneToOne vs @ManyToOne with Hibernate - no difference?

查看:553
本文介绍了JPA单向@OneToOne vs @ManyToOne与Hibernate - 没有区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 Pro JPA 2 的书籍,单向@ManyToOne和@OneToOne之间的主要区别在于@ OneToOne:


源实体只有一个实例可以引用同一个目标实体实例。
换句话说,目标实体实例是在源实体实例中不共享的
。在数据库中,这相当于在
源外键列(即源实体表中的外键列)上具有唯一性约束。


问题是,当我在实体上创建这样的映射并让Hibernate创建模式时,根本没有创建任何独特的约束。为什么?正因为如此,如果我必须明确地为映射定义唯一约束,@ManyToOne和@OneToOne之间没有区别。我可以为他们两人做,而且没有任何区别。是否正确的行为?

解决方案

如果关联是ManyToOne,则没有理由使用OneToOne,反之亦然。使用适当的注释,它反映了关联的基数的真实性。不这样做只会混淆应用程序的开发人员,如果不是Hibernate本身。



源的唯一性是否在数据库中受到限制并不会改变任何内容对于Hibernate。根据我的经验,Hibernate 确实在OneToOne的情况下创建唯一约束,如果不是,那么您应该创建它(我不会使用Hibernate创建模式,除了一个快速的'肮脏的演示应用程序)。

但是,当然,如果有一个唯一的约束,并且您尝试创建两个具有相同目标实体的不同实体,那将由于数据库唯一约束抛出错误而失败。


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?

解决方案

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.

这篇关于JPA单向@OneToOne vs @ManyToOne与Hibernate - 没有区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆