开发者

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

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 tab开发者_高级运维le.

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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜