Return treated message when it occurs (with.mysql.jdbc.exceptions.jdbc4.Mysqlintegrityconstraintviolationexception:)

Asked

Viewed 247 times

-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:

inserir a descrição da imagem aqui

  • 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.

1 answer

0


You can try to do the following:

public void delete(Integer id) {
    find_id(id);
    try {
        categoriaRepository.deleteById(id);
        // a próxima linha faz o commit imediato provocando o Exception
        categoriaRepository.flush();
    } catch (org.springframework.dao.DataIntegrityViolationException e) {
        throw new RuntimeException("Não é possível excluir uma categoria que possui produtos");
    }
}
  • Great William, good morning! Thanks for your help, it worked out! What a gift bless you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.