Why @OneToOne is allowing duplicate associations?

坚强是说给别人听的谎言 提交于 2019-11-30 06:21:31

@OneToOne is annotating the Java to express the idea of the relationship between the two classes. If this was a @OneToMany then we'd have a collection instead. So reading the annotations we understand the realtionships, and the JPA runtime also understands those.

The actual policing of the one-to-one is performed in the database - we need the schema to have the uniqueness constraints. The @JoinColumn expresses how that relationship is manifest in the DatabaseSchema.This can be useful if we are generating the schema.

However in many cases we use bottom-up tools to generate the Java from the schema. In this case there's no actual need for the Java annotations to reflect the database constraints, from a Java perspective we just see the relationship.

An intelligent compiler might warn us if the semantics of our @JoinColumn doesn't match the @oneToOne, but I'm not sure whether current implementations do that.

OneToOne is an annotation describing the object model. It says what the cardinality of the association is. unique="true" is an indication to the "model-to-ddl" tool that there should be a unique cosntraint on this column. You can use such a tool, but you're also free to create and maintain the database schema yourself.

Whatever you choose to do, the JPA engine doesn't make a query each time the OneToOne association is modified to check that the cardinality is respected. All it does is assuming that the code is correct, and the unique constraint in the database will make sure that the cardinality is respected.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!