【发布时间】:2020-03-16 11:04:20
【问题描述】:
我尝试将对象 Run 保存到数据库。我定义了 Run 和 City 之间的关系。一个城市可以有很多次运行。我遇到了 city_id 的问题。一片空白。
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause
java.sql.SQLIntegrityConstraintViolationException: Column 'city_id' cannot be null
我的实体和控制器: 城市
@Entity
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "cities")
public class City {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "city_id")
private long id;
@OneToMany(mappedBy = "city", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<Run> runs = new ArrayList<>();
private String name;
}
运行
@Entity
@Builder
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "runs")
public class Run {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "name_run")
private String nameRun;
@Column(name = "distance")
private double distance;
@Column(name = "date")
private Date date;
@Column(name = "my_time")
private String myTime;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "city_id", nullable = false)
@OnDelete(action = OnDeleteAction.CASCADE)
@JsonIgnore
private City city;
}
控制器
@CrossOrigin
@RestController
@RequestMapping("/api/")
public class RunController {
private RunRepository runRepository;
private RunService runService;
public RunController(RunRepository runRepository, RunService runService) {
this.runRepository = runRepository;
this.runService = runService;
}
@GetMapping("runs")
public ResponseEntity<List<Run>> getRuns() {
return runService.getRuns();
}
@PostMapping("runs")
public ResponseEntity addRun(@RequestBody Run run) {
return new ResponseEntity<>(runRepository.save(run), HttpStatus.OK);
}
}
我想将运行保存在数据库中。 我的测试请求如下所示:
{ "nameRun": "测试", “距离”:“5.0”, "日期":"2020-12-12", "我的时间":"50:40", “城市”:“测试1” }
Intelijj 中评估表达式的结果:
为什么城市 = null?这里是映射错误吗?
【问题讨论】:
-
你使用什么数据库?您能否提供您的
cities和runs表定义(ddl sql)。
标签: java hibernate hibernate-mapping