Spring Boot bidirectional ManyToOne constraint

318 views Asked by At

Here are my 2 entities with a bidirectional ManyToOne relation. I deleted getters and setters to simplify the code.

@Entity
public class City {
 
 @Id
 @GeneratedValue(strategy = GenerationType.AUTO)
 protected int id;

 @Column(nullable = false, length = 50)
 protected ZonedDateTime creationDate;

 @Column(nullable = false, length = 50)
 protected ZonedDateTime updatedDate;

 @NotNull
 @Size(min = 3, max = 20)
 @Column(unique = true)
 protected String name;
   
    @OneToMany(mappedBy = "id")
    @JsonBackReference
    protected Collection<Spot> spots;
}

@Entity
@Table(uniqueConstraints = @UniqueConstraint(columnNames = { "name", "address", "city_id" }))
@JsonIgnoreProperties(ignoreUnknown = true)
public class Spot {
 
 @Id
 @GeneratedValue(strategy = GenerationType.AUTO)
 protected int id;

 @Column(nullable = false, length = 50)
 protected ZonedDateTime creationDate;

 @Column(nullable = false, length = 50)
 protected ZonedDateTime updatedDate;

 @NotNull
 @Size(min = 3, max = 30)
 protected String name;

 @NotNull
 @NotBlank
 protected String address;

 @NotNull
 @ManyToOne
 @JoinColumn(name = "city_id")
 // @JsonManagedReference
 protected City city;
}

enter image description here

Because of the second constraint, i can't add more spots than the number of cities. IDs allowed for Spot is in the range of <1 to number of cities>.

Here is the error i get :

Cannot add or update a child row: a foreign key constraint fails (`myDatabase`.`spot`, CONSTRAINT `FKo3x3ohxcttkl2at3yr1xviw1r` FOREIGN KEY (`id`) REFERENCES `city` (`id`))

Any idea ? thank you

0

There are 0 answers