我有两张表:
societe (
id SERIAL PRIMARY KEY,
...,
fk_adresse int NOT NULL
);
(fk_adresse是外键)
另一张表是
bureau (
fk_societe INT PRIMARY KEY NOT NULL,
...,
fk_convention INT NOT NULL,
....
);
fk_societe是"societe“表的主键,也是”societe“表的外键,fk_convention是外键
我的bureau的Java映射是:
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "fk_societe", nullable = false)
private Integer fkSociete;
@OneToOne(fetch = FetchType.LAZY, optional = true, cascade = CascadeType.ALL)
@JoinColumns({ @JoinColumn(name = "fk_societe", referencedColumnName = "id") })
private Societe societe;
....
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "fk_convention", referencedColumnName = "id")
private Convention convention;
....
我的控制器是
@RequestMapping(value = "/create", method = RequestMethod.POST, consumes = "application/x-www-form-urlencoded;application/json")
public void createBureau(Bureau bureau){
bureauRepository.save(bureau);
}
@GetMapping("/bureaux")
public List<Bureau> getAllBureaux() {
return bureauRepository.findAll();
}
//recherche de bureau
@GetMapping("/{id}")
public ResponseEntity<Bureau> getBureauById(@PathVariable(value = "id") Integer id)
throws ResourceNotFoundException {
Bureau bureau = bureauRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException("Bureau not found");
return ResponseEntity.ok().body(bureau);
}
搜索一个局和所有局的列表可以正常工作,但创建一个局不起作用。在我的societe表中,我有一个id为42的societe,因此我使用Postman和以下数据发送了一个创建(POST)请求:
fk_societe 42
fk_devise 1
fk_langue 67
fk_convention 2
est_4_e_directive true
est_transitoire false
邮递员告诉我有一个500错误,在我的控制台中,我有以下错误
2020-10-16 11:50:07.115 ERROR 8368 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : ERREUR: une valeur NULL viole la contrainte NOT NULL de la colonne ½ fk_societe ╗ dans la relation ½ bureau ╗
DÚtailá: La ligne en Úchec contient (null, 0, 0, null, f, f).
它被翻译成
ERROR: a NULL value violates the NOT NULL constraint of the fk_societe column in the bureau relationship
Details : the failing line contains (null, 0, 0, null, f, f).
可能我的外键映射不正确...
发布于 2020-10-16 10:24:30
尝试通过以下方式更正您对该局的映射:
@Id
@Column(name = "fk_societe", nullable = false)
private Integer fkSociete;
@MapsId
@OneToOne(fetch = FetchType.LAZY, optional = false, cascade = CascadeType.ALL)
@JoinColumn(name = "fk_societe")
private Societe societe;
因为您使用与实体id相同的列fk_societe
和指向另一个实体的外键,所以在这里应该使用@MapsId
annotation。
https://stackoverflow.com/questions/64387012
复制相似问题