why hibernate creates a join table for unidirectional OneToMany?

后端 未结 2 1581
太阳男子
太阳男子 2021-01-01 19:44

Why hibernate uses a join table for these classes?

@Entity
public class CompanyImpl {
    @OneToMany
    private Set flights;


@Entity
public          


        
相关标签:
2条回答
  • 2021-01-01 19:57

    Because that's how it's designed, and what the JPA spec tells it to map such an association. If you want a join column in the Flight table, use

    @Entity
    public class CompanyImpl {
        @OneToMany
        @JoinColumn(name = "company_id")
        private Set<Flight> flights;
    }
    

    This is documented.

    0 讨论(0)
  • 2021-01-01 20:03

    Hibernate uses an association table to map the relationship, whilst the other table which is the many side does not not that any table exist. It will then create a mapper instead.

    The documentation states that using @OneToMany and @ManyToMany you can map Collections, Lists, Maps and Sets of associated entities.

    if you do not specify @joincolumn, this is as regards your question, a unidirectional one to many with join table is used. The table name is the concatenation of the owner table name, _, and the other side table name. The foreign key name(s) referencing the owner table is the concatenation of the owner table, _, and the owner primary key column(s) name.

    So if you do not want to create a join table(mapper) using the one to many you may have to specify the @joinColumn.

    @Entity
    public class CompanyImpl {
        @OneToMany
         @JoinColumn(name=flights_id)
        private Set<Flight> flights;
    
    
    @Entity
    public class Flight {
    
    0 讨论(0)
提交回复
热议问题