【发布时间】:2017-06-05 05:51:17
【问题描述】:
我使用 Hibernate 并且我有实体:
@Data
@Entity
public class Country {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private long id;
@Column(name = "country_nm")
private String countryName;
}
@Data
@Entity
public class City {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private long id;
@Column(name = "city_nm")
private String cityName;
}
国家可以有很多城市,城市只有一个国家。 关联这些实体的最佳方式是什么?
1) 在City 类中添加City city 字段并在其上方添加@ManyToOne 和@JoinColumn 注释?因此,我们将有两个表:country 和 city,city 表将有 country_id 列。
2) 在Country 类和@OneToMany(mappedBy='country') 上面添加Country country 字段并在City 类中添加City city 字段并在它上面添加@ManyToOne 注释?在这种情况下,将有三个表:country、city 和组合表country_city
【问题讨论】:
-
没有“最好”的方法。这一切都取决于你想要什么和需要什么。但是,您描述的两种方式是不正确的,并且您对如何映射双向关联的理解是错误的。阅读休眠手册。
-
谢谢,我正在做
标签: hibernate one-to-many many-to-one mappedby