Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 4535

@JoinColumn Annotation Explained

$
0
0

1. Introduction

The annotation javax.persistence.JoinColumn marks a column for as a join column for an entity association or an element collection.

In this quick tutorial, we’ll show some examples of basic @JoinCloumn usage.

2. @OneToOne Mapping Example

The @JoinColumn annotation combined with a @OneToOne mapping indicates that a given column in the owner entity refers to a primary key in the reference entity:

@Entity
public class Office {
    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "addressId")
    private Address address;
}

The above code example will create a foreign key linking the Office entity with the primary key from the Address entity. The name of the foreign key column in the Office entity is specified by name property.

3. @OneToMany Mapping Example

When using a @OneToMany mapping we can use the mappedBy parameter to indicate that the given column is owned by another entity.

@Entity
public class Employee {
 
    @Id
    private Long id;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "employee")
    private List<Email> emails;
}

@Entity
public class Email {
 
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "employee_id")
    private Employee employee;
}

In the above example, Email (the owner entity) has a join column employee_id that stores the id value and has a foreign key to the Employee entity.

4. @JoinColumns

In situations when we want to create multiple join columns we can use the @JoinColumns annotation:

@Entity
public class Office {
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumns({
        @JoinColumn(name="ADDR_ID", referencedColumnName="ID"),
        @JoinColumn(name="ADDR_ZIP", referencedColumnName="ZIP")
    })
    private Address address;
}

The above example will create two foreign keys pointing to ID and ZIP columns in the Address entity:

5. Conclusion

In this article, we’ve learned how to use the @JoinColumn annotation. We’ve shown examples how to create both single entity association and element collection.

As always, all source code is available over on GitHub.


Viewing all articles
Browse latest Browse all 4535

Trending Articles