我正在使用 SpringBoot,所以首先讓我們說,我想創建一個 Country,在使用 JSON 進行 POST 之后,我該如何做其他 POST 來創建一個 City 并將其添加到創建的 Country 中?
或者我不能用 JSON 做到這一點?
如果讓 FK 指向名稱而不是 ID 是一個好主意,在我的腦海中它的作業原理相同 bc 是唯一鍵,對嗎?
謝謝!
國家代碼:
@Entity
@Table(uniqueConstraints = {
@UniqueConstraint(name = "country_name",columnNames = "name")
})
@Getter @Setter @RequiredArgsConstructor @NoArgsConstructor @ToString
public class Country implements Serializable {
@Id
@Column(updatable = false, nullable = false, unique = true)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NonNull
private String name;
@OneToMany(mappedBy = "country", cascade = CascadeType.ALL, orphanRemoval = true)
private Set<City> cities = new HashSet<>();
}
城市代碼:
@Entity
@Table(uniqueConstraints = {
@UniqueConstraint(name = "city_name",columnNames = "name")
})
@Getter @Setter @RequiredArgsConstructor @NoArgsConstructor @ToString
public class City implements Serializable {
@Id
@Column(updatable = false, nullable = false, unique = true)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NonNull
private String name;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "country_name", referencedColumnName = "name", nullable = false,
foreignKey=@ForeignKey(name = "FK_country_city"))
private Country country;
@OneToMany(mappedBy = "city", cascade = CascadeType.ALL, orphanRemoval = true)
private Set<Neighborhood> neighborhoods = new HashSet<>();
}
小區代碼:
@Entity
@Table(uniqueConstraints = {
@UniqueConstraint(name = "neighborhood_name",columnNames = "name")
})
@Getter @Setter @RequiredArgsConstructor @NoArgsConstructor @ToString
public class Neighborhood implements Serializable {
@Id
@Column(updatable = false, nullable = false, unique = true)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NonNull
private String name;
@NonNull
private String neighborhoodType;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "city_name", referencedColumnName = "name", nullable = false,
foreignKey=@ForeignKey(name = "FK_city_neighborhood"))
private City city;
}
uj5u.com熱心網友回復:
所以首先你需要做 POST 請求來創建 Country 物件:
{
"name": "USA",
"cities": []
}
其次,您需要執行 POST 請求來創建 City 物件并將欄位 country 與主鍵 (PK):
{
"name": "Huston",
"country": 1,
"neighborhoods": []
}
實際上就是這樣。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/515690.html
上一篇:資料庫未創建
