views:

122

answers:

1

Does it make sense to have a @OneToOne member contain a @ForiegnKey annotation.

@Entity 
class User {

    @Id
    @GeneratedValue(strategy = IDENTITY)

    int id;

   @OneToOne
   @ForeignKey
   @JoinColumn(name = "home_address_id", referencedColumnName = "id")
   Address homeAddress;

}

@Entity 
class Address {
    @Id
    @GeneratedValue(strategy = IDENTITY)
    int id;
}
+4  A: 

I don't think it is necessary as The @OneToOne mapping should implicitely create a foreign key for the column.

On the other hand, if you think it will help you and other developers to understand the code easier and it doesn't cause any problems, you can leave it there.

However, it seems that the ForeingKey annotation is hibernate specific where the OneToOne annotation is part of the Java Persistence API. This might support the idea of taking it out.

Aleksi
It does seem to create an implicit foreign key if we remove the annotation. I was using the @ForeignKey annotation to provide a user friendly name for the foreign key. I wasn't sure on whether this was key was automatically created. Thanks for your answer.
Samuel