@JoinColumn Annotation Explained

November 9, 2020

You can use @joinColumn annotation in javax.persistence.JoinColumn  to define the relationship between two entities.

@OneToOne Mapping

You can have the Person and Address relationship

@OneToMany Mapping

MobilePhone has many Accesories

MobilePhone Entity has @OneToMany annotation and mappedBy attribute named moblePhone


@Entity
public class MobilePhone {
    @Id @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    private String name;

    @OneToMany(cascade= CascadeType.ALL, mappedBy="mobilePhone")
    private List<Accessory> accessories;
}

Accessory Entity has @ManyToOne annotation and @JoinColumn annotation

@Entity
public class Accessory {
    @Id @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    private String name;

    @ManyToOne
    @JoinColumn(name="mobile_phone_id", nullable=false)
    private MobilePhone mobilePhone;

}

@ManyToMany Mapping