-2
Can anyone help me return a message dealt with when it occurs
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationExcept
ion: Cannot delete or update a parent row: a foreign key constraint
fails ('loja'.'produto', CONSTRAINT 'id' FOREIGN KEY ('categoria_id')
REFERENCES 'categoria' ('id'))
When trying to delete a category in which already has product associated want returns the message that it is not possible to exclude, however I am not able to perform this treatment.
**Entidade:**
@Table(name = "categoria")
@Entity
public class Categoria implements Serializable {
/*Attributes*/
private static final long serialVersionUID = 1L;
@Id
@SequenceGenerator(name = "CATEGORIA_ID", sequenceName = "CATEGORIA_SEQ", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "CATEGORIA_ID")
private Integer id;
private String nome;
private String ativo;
/*======================= Associações =======================*/
/* Uma categoria tem vários produtos */
@OneToMany(mappedBy = "categoria")
private List<Produto> produtos = new ArrayList<>();;
/*===================== Fim Associações =====================*/
**RESOURCE:**
/*----------------------------------------------------*
* delete - Categoria
*----------------------------------------------------*/
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public ResponseEntity<Void> delete(@PathVariable Integer id) {
categoriaService.delete(id);
return ResponseEntity.noContent().build();
}
**SERVICE:**
public void delete(Integer id) {
find_id(id);
try {
categoriaRepository.deleteById(id);
} catch (Exception e) {
if (e instanceof com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException) {
throw new DataIntegrityException("Não é possível excluir uma categoria que possui produtos");
}
}
}
Error displayed in Insonimnia or Postman:
Thanks to our friend William it worked correctly. SPRING BOOT was not entering the line of Cath, after entering the command categoriaRepository.flush(); he commits immediately causing the exception.
– Alex Rocha