gpt4 book ai didi

java - 外键为空 : Hibernate Spring

转载 作者:行者123 更新时间:2023-12-02 08:52:08 25 4
gpt4 key购买 nike

我尝试将对象 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;
}

Controller


@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","myTime":"50:40",“城市”:“测试1”}

Intelijj 中评估表达式的结果:

enter image description here

为什么城市 = null?这里是映射错误吗?

最佳答案

你可以尝试使用这个 json 但你需要在 json 中传递城市 ID。

{
"nameRun": "test",
"distance": "5.0",
"date": "2020-12-12",
"myTime": "50:40",
"city": {
"id": 1,
"name": "test1"
}
}

谢谢

关于java - 外键为空 : Hibernate Spring,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60704774/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com