我之间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列上的所有行都为空。我想念什么?

最佳答案

这是Hibernate中的常见情况,其原因是未设置关系的逆关系:

Citizen c = new Citizen();
WeeklyCare w = new WeeklyCare();
c.getWeeklyCare().add(w);

//The missing link:
w.setCitizen(c);

citizenRepository.save(c);

我不确定在您的Web服务请求中如何配置它...

08-18 20:15