4

The Hibernate Docs (2.2.5.1. One-to-one) present the following example:

@Entity
public class Customer implements Serializable {
    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name="passport_fk")
    public Passport getPassport() {
        ...
    }

@Entity
public class Passport implements Serializable {
    @OneToOne(mappedBy = "passport")
    public Customer getOwner() {
    ...
}   

As I understand, Customer has a one-to-one relationship with Passport, where Customer is the owner, i.e. responsible for cascading updates to Passport. The mappedBy in Passport indicates that it has a one-to-one relationship with Customer, but it is not responsible for cascading updates to Customer.

Customer has a foreign-key constraint on Passport, as well as vice-versa for Passport to Customer.

What is the meaning of the @JoinColumn(name="passport_fk") of Customer? How about passport in the mappedBy of Passport? Are they the table columns representing their respective foreign keys?

Kevin Meredith
  • 41,036
  • 63
  • 209
  • 384

1 Answers1

7
What is the meaning of the @JoinColumn(name="passport_fk") of Customer?

This means that passport_fk field will be created inside Customer table, since it belongs here, this table is treated as the owner of the relationship (you seem to get that though).

 How about passport in the mappedBy of Passport

Since this is annotated with mappedBy it shows that this si NOT the owner, and that the Owner is Customer (the field that is annotated). name attribute is telling Hibernate where to find the information about the FK mapping (inside Customer there is a getPassport method). No additional fields will be created in Passport.

Eugene
  • 117,005
  • 15
  • 201
  • 306
  • So `@OneToOne(mappedBy = "passport")` means there's a 1-to-1 association, and that `Customer`'s `passport` field maps it(the passport)? Also, is it possible to create a Passport without an already existing Customer? In other words, does Passport have a fk to customer? – Kevin Meredith Jan 25 '14 at 15:19
  • @KevinMeredith yes OneToOne means a 1-to-1, obvious. And no you can' t create a Child without a parent. Think about it at a DB level, since u do not have a PK already in the database, u can't insert a Child. – Eugene Jan 26 '14 at 20:27
  • based on this answer (http://stackoverflow.com/a/9108618/409976), then my understanding is that `Passport` would not have a foreign key constraint to `Customer`. – Kevin Meredith Jan 27 '14 at 01:30
  • @KevinMeredith finally I has some time to re-read the question. As you have the mappings right you can insert both the child and parent alone without a problem, this is because Hibernate by default does not create a unique constraint on FK, they will simply be null. So even if you have a FK constraint it will not be enforced, unless, for example you put the optional=false on the OneToOne. – Eugene Jan 27 '14 at 08:11