why hibernate creates a join table for unidirectional OneToMany?

人盡茶涼 提交于 2019-11-30 01:43:36

问题


Why hibernate uses a join table for these classes?

@Entity
public class CompanyImpl {
    @OneToMany
    private Set<Flight> flights;


@Entity
public class Flight {

I don't want neither a join table nor a bidirectional association:(


回答1:


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.




回答2:


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 {


来源:https://stackoverflow.com/questions/13941801/why-hibernate-creates-a-join-table-for-unidirectional-onetomany

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!