Why @OneToOne is allowing duplicate associations?

前端 未结 2 2071
难免孤独
难免孤独 2020-12-28 17:17

I have User and Address classes as follows:

class User
{
   ...
   ...
   @OneToOne( cascade=CascadeType.ALL)
   @JoinColumn(name=\"addr_id\")
   private Add         


        
2条回答
  •  感动是毒
    2020-12-28 18:00

    @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.

提交回复
热议问题