gpt4 book ai didi

java - 保存对象后外键为空

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:05:57 26 4
gpt4 key购买 nike

我在 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,它接收一个 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);

虽然我不确定这是如何在您的网络服务请求中配置的...

关于java - 保存对象后外键为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55433706/

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