I am using SpringBoot, so lets say first, I want to make a Country, and after doing that POST with JSON how can I do other POST to create a City and adding it to the Country created?
Or I cant do it with JSON?
And idk if is a good idea having the FK pointing the name instead of the ID, in my head it works the same bc is an unique key, right?
Thanks!
Country code:
@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<>();
}
City code:
@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<>();
}
Neiborhood code:
@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;
}
CodePudding user response:
So first you need to do the POST request to create Country object:
{
"name": "USA",
"cities": []
}
Second you need to do the POST request to create the City object and put the field country with the Primary Key (PK):
{
"name": "Huston",
"country": 1,
"neighborhoods": []
}
That's pretty much it actually.