我有两个表:
societe (
id SERIAL PRIMARY KEY,
...,
fk_adresse int NOT NULL
);
(fk_addresse是外键(
另一张表是
bureau (
fk_societe INT PRIMARY KEY NOT NULL,
...,
fk_convention INT NOT NULL,
....
);
fk_societe既是";局;表和指向"的外键;societe";表和fk_convention是一个外键
我的局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的societ,所以我用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).
也许我的外键没有正确映射。。。
尝试以以下方式更正您的局映射:
@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
注释。