OneToMany 協會
為了說明 OneToMany 的關係,我們需要 2 個實體,例如國家和城市。一個國家有多個城市。
在下面的 CountryEntity 中,我們為 Country 定義了一組城市。
@Entity
@Table(name = "Country")
public class CountryEntity implements Serializable
{
private static final long serialVersionUID = 1L;
@Id
@Column(name = "COUNTRY_ID", unique = true, nullable = false)
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Integer countryId;
@Column(name = "COUNTRY_NAME", unique = true, nullable = false, length = 100)
private String countryName;
@OneToMany(mappedBy="country", fetch=FetchType.LAZY)
private Set<CityEntity> cities = new HashSet<>();
//Getters and Setters are not shown
}
現在是城市實體。
@Entity
@Table(name = "City")
public class CityEntity implements Serializable
{
private static final long serialVersionUID = 1L;
@Id
@Column(name = "CITY_ID", unique = true, nullable = false)
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Integer cityId;
@Column(name = "CITY_NAME", unique = false, nullable = false, length = 100)
private String cityName;
@ManyToOne(optional=false, fetch=FetchType.EAGER)
@JoinColumn(name="COUNTRY_ID", nullable=false)
private CountryEntity country;
//Getters and Setters are not shown
}