what is @JoinColumn and how it is used in Hibernate

A unidirectional association via a join table

@Entity
class Patient {

    @OneToMany
    private Collection<Vehicle> vehicles = new ArrayList<Vehicle>();

}

@Entity
class Vehicle {

}

A bidirectional association via a join table

@Entity
class Patient {

    @OneToMany
    private Collection<Vehicle> vehicles = new ArrayList<Vehicle>();

}

@Entity
class Vehicle {

    @ManyToOne(fetch = FetchType.LAZY)
    private Patient patient;

}

A unidirectional association via a foreign key

@Entity
class Patient {

    @OneToMany
    @JoinColumn
    private Collection<Vehicle> vehicles = new ArrayList<Vehicle>();

}

@Entity
class Vehicle {

}

A bidirectional association via a foreign key

@Entity
class Patient {

    @OneToMany(mappedBy = "patient")
    private Collection<Vehicle> vehicles = new ArrayList<Vehicle>();

}

@Entity
class Vehicle {

    @ManyToOne(fetch = FetchType.LAZY)
    private Patient patient;

}

We don’t need to use @JoinColumn on the Vehicle side, Hibernate assumes
it by default. Sometimes I use it just to stress it out (another case, when we want to specify a join column name).

    @Entity
    class Vehicle {
    
        @ManyToOne(fetch = FetchType.LAZY)
        @JoinColumn
        private Patient patient;
    
    }

A bidirectional association via a foreign key with a foreign column name specification

@Entity
class Patient {

    @OneToMany(mappedBy = "patient")
    private Collection<Vehicle> vehicles = new ArrayList<Vehicle>();

}

@Entity
class Vehicle {

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="patient_id")
    private Patient patient;

}

This is the basic starting point of using @JoinColumn.

To verify that the foreign key(patient_id in the Vehicle table) is really mapped in the patients table you can use @JoinColumn(nullable = false)

@Entity
class Vehicle {

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="patient_id", nullable = false)
    private Patient patient

}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)