我与市民之间有关系:
@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:
@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接收一个市民列表和一个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 citizens) {
citizenRepository.saveAll(citizens);
return new ResponseEntity(new ApiResponse(true, "Filen er blevet indlæst", "CITIZENS_SAVED"), HttpStatus.OK);
}
此后,当我查看数据库的weekly_care表时,citizen_id列上的所有行均为null.我想念什么?
解决方法:
这是Hibernate中的常见情况,其原因是未设置关系的倒数:
Citizen c = new Citizen();
WeeklyCare w = new WeeklyCare();
c.getWeeklyCare().add(w);
//The missing link:
w.setCitizen(c);
citizenRepository.save(c);
我不确定如何在您的Web服务请求中配置它…
标签:hibernate,java
来源: https://codeday.me/bug/20191211/2105403.html