避免 Hibernate 中的关系表将一对多(或一对多)关联映射到数据库表
我是休眠新手。我注意到在Hibernate中,将java类映射到数据库表中通常涉及关系表,甚至有时关系表不是必需的(例如在一对多关系中或相反)。
例如:
我是一个Company类和一个Flight类,其中一个公司可以有多个航班(从Company到Flight的一对多关联)。
我有以下使用 hibernate 注释的代码:
@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
......
}
类已成功映射到数据库中。有三个表,分别是:
- COMPANY(一个 ID 字段)
- FLIGHT(一个 ID 字段和一个 COMP_ID 字段)
- COMPANY_MANY_TO_ONE_FLIGHT(两个字段:MANY_TO_ONE_COMPANY_id 和 Flights_id )
但是,最后一个表 COMPANY_MANY_TO_ONE_FLIGHT 是一个关系hibernate添加的表,这是多余的。
显然,FLIGHT表中存在外键COMP_ID,删除冗余关系表是合理的。
我怎样才能避免这种情况呢?就像通过修改注释一样。
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:
- COMPANY(an ID field)
- FLIGHT(an ID field and an COMP_ID field)
- 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试在@OneToMany注释中使用mappedBy属性:
您可以在此处查找mappend与hibernate注释的常见关联:
http://docs.jboss .org/hibernate/stable/annotations/reference/en/html/entity.html#entity-mapping-association
try using the mappedBy property in the @OneToMany annotation:
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