保存对象后,外键为空

时间:2019-03-30 16:58:21

标签: java hibernate

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

1 个答案:

答案 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服务请求中该如何配置...