what is @JoinColumn and how it is used in Hibernate

后端 未结 5 563
死守一世寂寞
死守一世寂寞 2020-11-28 06:08

I have been reading a lot about @JoinColumn but I still don\'t get the idea behind it.

Patient Table

CREATE TABLE patient (
patient_id BIGINT NOT NUL         


        
5条回答
  •  攒了一身酷
    2020-11-28 06:29

    A unidirectional association via a join table

    @Entity
    class Patient {
    
        @OneToMany
        private Collection vehicles = new ArrayList();
    
    }
    
    @Entity
    class Vehicle {
    
    }
    

    A bidirectional association via a join table

    @Entity
    class Patient {
    
        @OneToMany
        private Collection vehicles = new ArrayList();
    
    }
    
    @Entity
    class Vehicle {
    
        @ManyToOne(fetch = FetchType.LAZY)
        private Patient patient;
    
    }
    

    A unidirectional association via a foreign key

    @Entity
    class Patient {
    
        @OneToMany
        @JoinColumn
        private Collection vehicles = new ArrayList();
    
    }
    
    @Entity
    class Vehicle {
    
    }
    

    A bidirectional association via a foreign key

    @Entity
    class Patient {
    
        @OneToMany(mappedBy = "patient")
        private Collection vehicles = new ArrayList();
    
    }
    
    @Entity
    class Vehicle {
    
        @ManyToOne(fetch = FetchType.LAZY)
        private Patient patient;
    
    }
    

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

    @Entity
    class Patient {
    
        @OneToMany(mappedBy = "patient")
        private Collection vehicles = new ArrayList();
    
    }
    
    @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
    
    }
    

提交回复
热议问题