我与Citizen
之间有关系:
@Entity
@Table(name = "citizens")
public class Citizen {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Size(max = 10, min = 10, message = "CPR must be exactly 10 characters")
private String cpr;
@OneToMany(mappedBy = "citizen", cascade = CascadeType.ALL, orphanRemoval = true)
private List<WeeklyCare> weeklyCare;
}
和WeeklyCare
:
@Entity
public class WeeklyCare {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "citizen_id")
private Citizen citizen;
}
我有一个REST API,该API分别接收Citizen
列表和WeeklyCare
列表并保存它们:
@Autowired
private CitizenRepository citizenRepository;
@CrossOrigin(origins = "http://localhost:4200")
@PostMapping(path = "/add") // Map ONLY GET Requests
@Secured({"ROLE_ADMIN", "ROLE_DATAMANAGER"})
public ResponseEntity addNewCitizens(
@RequestBody List<Citizen> citizens) {
citizenRepository.saveAll(citizens);
return new ResponseEntity(new ApiResponse(true, "Filen er blevet indlæst", "CITIZENS_SAVED"), HttpStatus.OK);
}
此后,当我查看数据库的weekly_care
表时,citizen_id
列上的所有行都为空。我想念什么?
答案 0 :(得分:2)
这是Hibernate
中的常见情况,其原因是未设置关系的倒数:
Citizen c = new Citizen();
WeeklyCare w = new WeeklyCare();
c.getWeeklyCare().add(w);
//The missing link:
w.setCitizen(c);
citizenRepository.save(c);
我不确定在您的Web服务请求中该如何配置...