Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate Mappedby Example

Tags:

java

hibernate

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?

like image 823
Kevin Meredith Avatar asked Mar 20 '23 20:03

Kevin Meredith


1 Answers

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.

like image 80
Eugene Avatar answered Mar 23 '23 11:03

Eugene