سؤال

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:(

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

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 {

I don't think the answers given above are elaborative enough so I hope this helps out

Reason. Why Hibernate creates a join table.

Hibernate creates a Join Table for a unidirectional OneToMany because by implementation, the foreign key is always kept at the many side. So in your example, the foreign key will be kept at the Flight table side AND thus to prevent having null values at the Many side Hibernate chooses to create a JoinTable.

Going by your example,

Every Flight will have a CompanyImpl column and if not set it would have to be null so to achieve the avoid nulls in certain Flight records, Hibernate chooses to have a JoinTable that will store the Ids for Flight and CompanyImpl.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top