How catch hibernate/jpa constraint violations in Spring Boot?












0














I have been unable to catch ConstraintViolationException (or DataIntegrityViolationException) in
ResponseEntityExceptionHandler.
I would like to return the jpa failure (e.g. which constraint violated) in the response.
(I prefer not to use @Valid on the method parameter and catch handleMethodArgumentNotValid).



...
import org.hibernate.exception.ConstraintViolationException;
import org.springframework.dao.DataIntegrityViolationException;

@ControllerAdvice
public class PstExceptionHandler extends ResponseEntityExceptionHandler {

@ExceptionHandler({ConstraintViolationException.class})
public ResponseEntity<Object> handleConstraintViolation(
ConstraintViolationException ex, WebRequest request) {

...

return new ResponseEntity<Object>(...);
}
}

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

@Entity
public class Student {

@Id
private Long id;

@NotNull
private String name;

@NotNull
@Size(min=7, message="Passport should have at least 7 characters")
private String passportNumber;

public Student() {
}

...

}

@RequestMapping(value = "/addstudent"...)
@ResponseBody
public ResponseEntity<Object> addStudent(@RequestBody StudentDto studentDto) {

Student student = new Student();
student.setId(studentDto.getId()); // 1L
student.setName(studentDto.getName()); // "helen"
student.setPassportNumber(studentDto.getPassportNumber()); // "321"

studentRepository.save(student);

return ResponseEntity.accepted().body(student);
}


thank you...










share|improve this question






















  • Could you try with HibernateException? just update this @ExceptionHandler({HibernateException.class}) and let me know what is your answer..?
    – Jonathan Johx
    Nov 4 '18 at 15:03












  • thank you - though it didn't resolve issue. problem persists.
    – Helen Reeves
    Nov 4 '18 at 15:37










  • Oh right, I have taken a look and Exceptions like ConstraintViolationException are not taken in account because they are extend from HIbernateException as I thought. So PersistenceException instead of AnyException that extends from HibernateException is thrown. So I think you should update something like this: @ExceptionHandler({PersistenceException.class}) public ResponseEntity<Object> handleConstraintViolation(PersistenceException ex, WebRequest request) { if (ex instanceof ConstraintViolationException) { ConstraintViolationException consEx = (ConstraintViolationException) ex;
    – Jonathan Johx
    Nov 4 '18 at 16:12








  • 1




    where/how do I vote? thanks
    – Helen Reeves
    Nov 5 '18 at 21:49






  • 1




    Just click on up button this comment xD or comments that were useful :)
    – Jonathan Johx
    Nov 10 '18 at 7:45
















0














I have been unable to catch ConstraintViolationException (or DataIntegrityViolationException) in
ResponseEntityExceptionHandler.
I would like to return the jpa failure (e.g. which constraint violated) in the response.
(I prefer not to use @Valid on the method parameter and catch handleMethodArgumentNotValid).



...
import org.hibernate.exception.ConstraintViolationException;
import org.springframework.dao.DataIntegrityViolationException;

@ControllerAdvice
public class PstExceptionHandler extends ResponseEntityExceptionHandler {

@ExceptionHandler({ConstraintViolationException.class})
public ResponseEntity<Object> handleConstraintViolation(
ConstraintViolationException ex, WebRequest request) {

...

return new ResponseEntity<Object>(...);
}
}

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

@Entity
public class Student {

@Id
private Long id;

@NotNull
private String name;

@NotNull
@Size(min=7, message="Passport should have at least 7 characters")
private String passportNumber;

public Student() {
}

...

}

@RequestMapping(value = "/addstudent"...)
@ResponseBody
public ResponseEntity<Object> addStudent(@RequestBody StudentDto studentDto) {

Student student = new Student();
student.setId(studentDto.getId()); // 1L
student.setName(studentDto.getName()); // "helen"
student.setPassportNumber(studentDto.getPassportNumber()); // "321"

studentRepository.save(student);

return ResponseEntity.accepted().body(student);
}


thank you...










share|improve this question






















  • Could you try with HibernateException? just update this @ExceptionHandler({HibernateException.class}) and let me know what is your answer..?
    – Jonathan Johx
    Nov 4 '18 at 15:03












  • thank you - though it didn't resolve issue. problem persists.
    – Helen Reeves
    Nov 4 '18 at 15:37










  • Oh right, I have taken a look and Exceptions like ConstraintViolationException are not taken in account because they are extend from HIbernateException as I thought. So PersistenceException instead of AnyException that extends from HibernateException is thrown. So I think you should update something like this: @ExceptionHandler({PersistenceException.class}) public ResponseEntity<Object> handleConstraintViolation(PersistenceException ex, WebRequest request) { if (ex instanceof ConstraintViolationException) { ConstraintViolationException consEx = (ConstraintViolationException) ex;
    – Jonathan Johx
    Nov 4 '18 at 16:12








  • 1




    where/how do I vote? thanks
    – Helen Reeves
    Nov 5 '18 at 21:49






  • 1




    Just click on up button this comment xD or comments that were useful :)
    – Jonathan Johx
    Nov 10 '18 at 7:45














0












0








0







I have been unable to catch ConstraintViolationException (or DataIntegrityViolationException) in
ResponseEntityExceptionHandler.
I would like to return the jpa failure (e.g. which constraint violated) in the response.
(I prefer not to use @Valid on the method parameter and catch handleMethodArgumentNotValid).



...
import org.hibernate.exception.ConstraintViolationException;
import org.springframework.dao.DataIntegrityViolationException;

@ControllerAdvice
public class PstExceptionHandler extends ResponseEntityExceptionHandler {

@ExceptionHandler({ConstraintViolationException.class})
public ResponseEntity<Object> handleConstraintViolation(
ConstraintViolationException ex, WebRequest request) {

...

return new ResponseEntity<Object>(...);
}
}

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

@Entity
public class Student {

@Id
private Long id;

@NotNull
private String name;

@NotNull
@Size(min=7, message="Passport should have at least 7 characters")
private String passportNumber;

public Student() {
}

...

}

@RequestMapping(value = "/addstudent"...)
@ResponseBody
public ResponseEntity<Object> addStudent(@RequestBody StudentDto studentDto) {

Student student = new Student();
student.setId(studentDto.getId()); // 1L
student.setName(studentDto.getName()); // "helen"
student.setPassportNumber(studentDto.getPassportNumber()); // "321"

studentRepository.save(student);

return ResponseEntity.accepted().body(student);
}


thank you...










share|improve this question













I have been unable to catch ConstraintViolationException (or DataIntegrityViolationException) in
ResponseEntityExceptionHandler.
I would like to return the jpa failure (e.g. which constraint violated) in the response.
(I prefer not to use @Valid on the method parameter and catch handleMethodArgumentNotValid).



...
import org.hibernate.exception.ConstraintViolationException;
import org.springframework.dao.DataIntegrityViolationException;

@ControllerAdvice
public class PstExceptionHandler extends ResponseEntityExceptionHandler {

@ExceptionHandler({ConstraintViolationException.class})
public ResponseEntity<Object> handleConstraintViolation(
ConstraintViolationException ex, WebRequest request) {

...

return new ResponseEntity<Object>(...);
}
}

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

@Entity
public class Student {

@Id
private Long id;

@NotNull
private String name;

@NotNull
@Size(min=7, message="Passport should have at least 7 characters")
private String passportNumber;

public Student() {
}

...

}

@RequestMapping(value = "/addstudent"...)
@ResponseBody
public ResponseEntity<Object> addStudent(@RequestBody StudentDto studentDto) {

Student student = new Student();
student.setId(studentDto.getId()); // 1L
student.setName(studentDto.getName()); // "helen"
student.setPassportNumber(studentDto.getPassportNumber()); // "321"

studentRepository.save(student);

return ResponseEntity.accepted().body(student);
}


thank you...







hibernate spring-mvc spring-boot spring-data-jpa






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 4 '18 at 14:15









Helen Reeves

156920




156920












  • Could you try with HibernateException? just update this @ExceptionHandler({HibernateException.class}) and let me know what is your answer..?
    – Jonathan Johx
    Nov 4 '18 at 15:03












  • thank you - though it didn't resolve issue. problem persists.
    – Helen Reeves
    Nov 4 '18 at 15:37










  • Oh right, I have taken a look and Exceptions like ConstraintViolationException are not taken in account because they are extend from HIbernateException as I thought. So PersistenceException instead of AnyException that extends from HibernateException is thrown. So I think you should update something like this: @ExceptionHandler({PersistenceException.class}) public ResponseEntity<Object> handleConstraintViolation(PersistenceException ex, WebRequest request) { if (ex instanceof ConstraintViolationException) { ConstraintViolationException consEx = (ConstraintViolationException) ex;
    – Jonathan Johx
    Nov 4 '18 at 16:12








  • 1




    where/how do I vote? thanks
    – Helen Reeves
    Nov 5 '18 at 21:49






  • 1




    Just click on up button this comment xD or comments that were useful :)
    – Jonathan Johx
    Nov 10 '18 at 7:45


















  • Could you try with HibernateException? just update this @ExceptionHandler({HibernateException.class}) and let me know what is your answer..?
    – Jonathan Johx
    Nov 4 '18 at 15:03












  • thank you - though it didn't resolve issue. problem persists.
    – Helen Reeves
    Nov 4 '18 at 15:37










  • Oh right, I have taken a look and Exceptions like ConstraintViolationException are not taken in account because they are extend from HIbernateException as I thought. So PersistenceException instead of AnyException that extends from HibernateException is thrown. So I think you should update something like this: @ExceptionHandler({PersistenceException.class}) public ResponseEntity<Object> handleConstraintViolation(PersistenceException ex, WebRequest request) { if (ex instanceof ConstraintViolationException) { ConstraintViolationException consEx = (ConstraintViolationException) ex;
    – Jonathan Johx
    Nov 4 '18 at 16:12








  • 1




    where/how do I vote? thanks
    – Helen Reeves
    Nov 5 '18 at 21:49






  • 1




    Just click on up button this comment xD or comments that were useful :)
    – Jonathan Johx
    Nov 10 '18 at 7:45
















Could you try with HibernateException? just update this @ExceptionHandler({HibernateException.class}) and let me know what is your answer..?
– Jonathan Johx
Nov 4 '18 at 15:03






Could you try with HibernateException? just update this @ExceptionHandler({HibernateException.class}) and let me know what is your answer..?
– Jonathan Johx
Nov 4 '18 at 15:03














thank you - though it didn't resolve issue. problem persists.
– Helen Reeves
Nov 4 '18 at 15:37




thank you - though it didn't resolve issue. problem persists.
– Helen Reeves
Nov 4 '18 at 15:37












Oh right, I have taken a look and Exceptions like ConstraintViolationException are not taken in account because they are extend from HIbernateException as I thought. So PersistenceException instead of AnyException that extends from HibernateException is thrown. So I think you should update something like this: @ExceptionHandler({PersistenceException.class}) public ResponseEntity<Object> handleConstraintViolation(PersistenceException ex, WebRequest request) { if (ex instanceof ConstraintViolationException) { ConstraintViolationException consEx = (ConstraintViolationException) ex;
– Jonathan Johx
Nov 4 '18 at 16:12






Oh right, I have taken a look and Exceptions like ConstraintViolationException are not taken in account because they are extend from HIbernateException as I thought. So PersistenceException instead of AnyException that extends from HibernateException is thrown. So I think you should update something like this: @ExceptionHandler({PersistenceException.class}) public ResponseEntity<Object> handleConstraintViolation(PersistenceException ex, WebRequest request) { if (ex instanceof ConstraintViolationException) { ConstraintViolationException consEx = (ConstraintViolationException) ex;
– Jonathan Johx
Nov 4 '18 at 16:12






1




1




where/how do I vote? thanks
– Helen Reeves
Nov 5 '18 at 21:49




where/how do I vote? thanks
– Helen Reeves
Nov 5 '18 at 21:49




1




1




Just click on up button this comment xD or comments that were useful :)
– Jonathan Johx
Nov 10 '18 at 7:45




Just click on up button this comment xD or comments that were useful :)
– Jonathan Johx
Nov 10 '18 at 7:45












2 Answers
2






active

oldest

votes


















0














Exceptions like ConstraintViolationException are not taken in account because they are extend from HibernateException. you can take a look exceptions in convert method that those are wrapped on Hibernate Exceptions.



@ExceptionHandler({TransactionSystemException.class})
public ResponseEntity<Object> handleConstraintViolation(TransactionSystemException ex, WebRequest request) {

if (ex.getCause() instanceof RollbackException) {
RollbackException rollbackException = (RollbackException) ex.getCause();
if (rollbackException.getCause() instanceof ConstraintViolationException) {
return new ResponseEntity<Object>(...);
}
...
}
...

return new ResponseEntity<Object>(...);
}





share|improve this answer































    0














    There're 3 ways:





    1. @Valid @Validated annotations.



      Once they used at parameter level, violations are available via method-injected Errors BindingResult type implementations.



    2. ConstraintViolationException is thrown each time an entity in non-valid state is passed to .save() or .persist() Hibernate methods.


    3. Entities may be manually validated via injected LocalValidatorFactoryBean.validate() method. The constraint violations then available through passed Errors object's implementation.
      Exactly, how @Valid @Validated annotations are internally implemented.







    share|improve this answer





















      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53141761%2fhow-catch-hibernate-jpa-constraint-violations-in-spring-boot%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      0














      Exceptions like ConstraintViolationException are not taken in account because they are extend from HibernateException. you can take a look exceptions in convert method that those are wrapped on Hibernate Exceptions.



      @ExceptionHandler({TransactionSystemException.class})
      public ResponseEntity<Object> handleConstraintViolation(TransactionSystemException ex, WebRequest request) {

      if (ex.getCause() instanceof RollbackException) {
      RollbackException rollbackException = (RollbackException) ex.getCause();
      if (rollbackException.getCause() instanceof ConstraintViolationException) {
      return new ResponseEntity<Object>(...);
      }
      ...
      }
      ...

      return new ResponseEntity<Object>(...);
      }





      share|improve this answer




























        0














        Exceptions like ConstraintViolationException are not taken in account because they are extend from HibernateException. you can take a look exceptions in convert method that those are wrapped on Hibernate Exceptions.



        @ExceptionHandler({TransactionSystemException.class})
        public ResponseEntity<Object> handleConstraintViolation(TransactionSystemException ex, WebRequest request) {

        if (ex.getCause() instanceof RollbackException) {
        RollbackException rollbackException = (RollbackException) ex.getCause();
        if (rollbackException.getCause() instanceof ConstraintViolationException) {
        return new ResponseEntity<Object>(...);
        }
        ...
        }
        ...

        return new ResponseEntity<Object>(...);
        }





        share|improve this answer


























          0












          0








          0






          Exceptions like ConstraintViolationException are not taken in account because they are extend from HibernateException. you can take a look exceptions in convert method that those are wrapped on Hibernate Exceptions.



          @ExceptionHandler({TransactionSystemException.class})
          public ResponseEntity<Object> handleConstraintViolation(TransactionSystemException ex, WebRequest request) {

          if (ex.getCause() instanceof RollbackException) {
          RollbackException rollbackException = (RollbackException) ex.getCause();
          if (rollbackException.getCause() instanceof ConstraintViolationException) {
          return new ResponseEntity<Object>(...);
          }
          ...
          }
          ...

          return new ResponseEntity<Object>(...);
          }





          share|improve this answer














          Exceptions like ConstraintViolationException are not taken in account because they are extend from HibernateException. you can take a look exceptions in convert method that those are wrapped on Hibernate Exceptions.



          @ExceptionHandler({TransactionSystemException.class})
          public ResponseEntity<Object> handleConstraintViolation(TransactionSystemException ex, WebRequest request) {

          if (ex.getCause() instanceof RollbackException) {
          RollbackException rollbackException = (RollbackException) ex.getCause();
          if (rollbackException.getCause() instanceof ConstraintViolationException) {
          return new ResponseEntity<Object>(...);
          }
          ...
          }
          ...

          return new ResponseEntity<Object>(...);
          }






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 21 '18 at 19:02

























          answered Nov 21 '18 at 17:28









          Jonathan Johx

          1,032211




          1,032211

























              0














              There're 3 ways:





              1. @Valid @Validated annotations.



                Once they used at parameter level, violations are available via method-injected Errors BindingResult type implementations.



              2. ConstraintViolationException is thrown each time an entity in non-valid state is passed to .save() or .persist() Hibernate methods.


              3. Entities may be manually validated via injected LocalValidatorFactoryBean.validate() method. The constraint violations then available through passed Errors object's implementation.
                Exactly, how @Valid @Validated annotations are internally implemented.







              share|improve this answer


























                0














                There're 3 ways:





                1. @Valid @Validated annotations.



                  Once they used at parameter level, violations are available via method-injected Errors BindingResult type implementations.



                2. ConstraintViolationException is thrown each time an entity in non-valid state is passed to .save() or .persist() Hibernate methods.


                3. Entities may be manually validated via injected LocalValidatorFactoryBean.validate() method. The constraint violations then available through passed Errors object's implementation.
                  Exactly, how @Valid @Validated annotations are internally implemented.







                share|improve this answer
























                  0












                  0








                  0






                  There're 3 ways:





                  1. @Valid @Validated annotations.



                    Once they used at parameter level, violations are available via method-injected Errors BindingResult type implementations.



                  2. ConstraintViolationException is thrown each time an entity in non-valid state is passed to .save() or .persist() Hibernate methods.


                  3. Entities may be manually validated via injected LocalValidatorFactoryBean.validate() method. The constraint violations then available through passed Errors object's implementation.
                    Exactly, how @Valid @Validated annotations are internally implemented.







                  share|improve this answer












                  There're 3 ways:





                  1. @Valid @Validated annotations.



                    Once they used at parameter level, violations are available via method-injected Errors BindingResult type implementations.



                  2. ConstraintViolationException is thrown each time an entity in non-valid state is passed to .save() or .persist() Hibernate methods.


                  3. Entities may be manually validated via injected LocalValidatorFactoryBean.validate() method. The constraint violations then available through passed Errors object's implementation.
                    Exactly, how @Valid @Validated annotations are internally implemented.








                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 21 '18 at 19:17









                  WildDev

                  1,07731949




                  1,07731949






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.





                      Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                      Please pay close attention to the following guidance:


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53141761%2fhow-catch-hibernate-jpa-constraint-violations-in-spring-boot%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      404 Error Contact Form 7 ajax form submitting

                      How to know if a Active Directory user can login interactively

                      Refactoring coordinates for Minecraft Pi buildings written in Python