问题
Is @JoinColum
implicitly specified when we use any association type annotation like @OneToOne
, @OneToMany
, etc.
Here is snippet from Student
entity in association with Laptop
entity
Case 1) Without using explicit @JoinColum
@OneToMany(cascade=CascadeType.ALL)
private List<Laptop> laptops=new ArrayList<Laptop>();
Case 2) Using explicit @JoinColum
@OneToMany(cascade=CascadeType.ALL)
@JoinColumn
private List<Laptop> laptops=new ArrayList<Laptop>();
When I check DEBUG
both cases have "almost" similar Binding
, i.e something like below.
1) So could I assume @JoinColum
is implicitly specified when @OneToMany
is specified? But wait I also noticed Hibernate is trying to refer to some totally strange table 'student_laptops' which I have not created anywhere (probably a join table).
So can someone describe whats exactly the flow going here?
Debug: private List<Laptop> laptops=new ArrayList<Laptop>();
//You can totally ignore this. Just specifying for any reference.
DEBUG - Binding column: Ejb3JoinColumn{logicalColumnName='null', referencedColumn='null', mappedBy=''}
DEBUG - Binding column: Ejb3Column{table=org.hibernate.mapping.Table(STUDENT), mappingColumn=laptops, insertable=true, updatable=true, unique=false}
DEBUG - Binding column: Ejb3Column{table=org.hibernate.mapping.Table(STUDENT), mappingColumn=null, insertable=true, updatable=true, unique=false}
DEBUG - Binding column: Ejb3Column{table=org.hibernate.mapping.Table(STUDENT), mappingColumn=element, insertable=true, updatable=true, unique=false}
DEBUG - Binding column: Ejb3Column{table=org.hibernate.mapping.Table(STUDENT), mappingColumn=laptops_KEY, insertable=true, updatable=true, unique=false}
DEBUG - Binding column: Ejb3JoinColumn{logicalColumnName='laptops_KEY', referencedColumn='null', mappedBy='null'}
DEBUG - Binding column: Ejb3JoinColumn{logicalColumnName='null', referencedColumn='null', mappedBy=''}
DEBUG - Binding column: Ejb3JoinColumn{logicalColumnName='null', referencedColumn='null', mappedBy=''}
DEBUG - Collection role: com.infiniteskills.data.entities.Student.laptops
DEBUG - Building property laptops
回答1:
Is @JoinColum implicitly specified when we use any association type annotation like @OneToOne, @OneToMany, etc.
The answer is: NO. Except the case when mappedBy
is used.
When you specify @JoinColumn
or mappedBy
(even without @JoinColumn
) Hibernate implies that you want to use an association via a foreign key (without a join table).
When you don't specify @JoinColumn
Hibernate uses a join table and creates it for you — student_laptops
in your case.
You can add a @JoinTable
annotation to stress the fact that you are using a jon table.
@OneToMany(cascade = CascadeType.ALL)
@JoinTable
private List<Laptop> laptops = new ArrayList<Laptop>();
来源:https://stackoverflow.com/questions/48679668/hibernate-why-is-binding-for-a-field-similar-weather-explicit-joincolum-annota