avoid relation table in Hibernate's mapping one-to-many(or one-to-many) association into db tables

早过忘川 提交于 2019-12-12 06:22:34

问题


I am new to Hibernate. I notice that in Hibernate, mapping the java classes into database tables often involve relation tables, even sometimes relation tables are not necessary(Like in a one-to-many relation or the opposite).

For example:

I am a Company class and a Flight class, in which a company can have many flights(a one to many association from Company to Flight).

I have the following code using hibernate annotations:

@Entity
@Table(name = "COMPANY")
public class Company {

    @Id
    private Long id;

    @OneToMany
    private Set<Flight> flights = new HashSet<Flight>();

    ......
    getter and setter methods
    ......
}



@Entity
@Table(name="FLIGHT")
public class Flight{
    @Id
    private Long id;

    @ManyToOne
    @JoinColumn(name = "COMP_ID")
    private Company ownerCompany;

    ......
    getter and setter methods
    ......

}

The classes are successfully mapped into database. And there are three tables, which are:

  1. COMPANY(an ID field)
  2. FLIGHT(an ID field and an COMP_ID field)
  3. COMPANY_MANY_TO_ONE_FLIGHT(two fields:MANY_TO_ONE_COMPANY_id and flights_id )

However, the last table COMPANY_MANY_TO_ONE_FLIGHT is a relation table added by hibernate, which is redundant.

Obviously, there is a foreign key COMP_ID in FLIGHT table and it is reasonable remove the redundant relation table.

And how can I avoid such circumstance? Like through modifying the annotations.


回答1:


try using the mappedBy property in the @OneToMany annotation:

@OneToMany(mappedBy="ownerCompany")
private Set<Flight> flights = new HashSet<Flight>();

you can look up common associations mappend with hibernate annotations here: http://docs.jboss.org/hibernate/stable/annotations/reference/en/html/entity.html#entity-mapping-association



来源:https://stackoverflow.com/questions/6649032/avoid-relation-table-in-hibernates-mapping-one-to-manyor-one-to-many-associat

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