Spring Boot双向ManyToOne约束

时间:2017-08-31 20:12:40

标签: spring many-to-one bidirectional

以下是我的2个具有双向ManyToOne关系的实体。我删除了getter和setter来简化代码。



@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;
}
&#13;
&#13;
&#13;

enter image description here

由于第二个限制因素,我无法添加比城市数量更多的地点。 Spot允许的ID范围为&lt; 1到城市数量&gt;。

以下是我得到的错误:

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

有什么想法吗?谢谢

0 个答案:

没有答案