How catch hibernate/jpa constraint violations in Spring Boot?
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
|
show 4 more comments
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
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
|
show 4 more comments
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
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
hibernate spring-mvc spring-boot spring-data-jpa
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
|
show 4 more comments
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
|
show 4 more comments
2 Answers
2
active
oldest
votes
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>(...);
}
add a comment |
There're 3 ways:
@Valid
@Validated
annotations.
Once they used at parameter level, violations are available via method-injected
Errors
BindingResult
type implementations.
ConstraintViolationException
is thrown each time an entity in non-valid state is passed to.save()
or.persist()
Hibernate methods.Entities may be manually validated via injected
LocalValidatorFactoryBean.validate()
method. The constraint violations then available through passedErrors
object's implementation.
Exactly, how@Valid
@Validated
annotations are internally implemented.
add a comment |
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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>(...);
}
add a comment |
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>(...);
}
add a comment |
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>(...);
}
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>(...);
}
edited Nov 21 '18 at 19:02
answered Nov 21 '18 at 17:28
Jonathan Johx
1,032211
1,032211
add a comment |
add a comment |
There're 3 ways:
@Valid
@Validated
annotations.
Once they used at parameter level, violations are available via method-injected
Errors
BindingResult
type implementations.
ConstraintViolationException
is thrown each time an entity in non-valid state is passed to.save()
or.persist()
Hibernate methods.Entities may be manually validated via injected
LocalValidatorFactoryBean.validate()
method. The constraint violations then available through passedErrors
object's implementation.
Exactly, how@Valid
@Validated
annotations are internally implemented.
add a comment |
There're 3 ways:
@Valid
@Validated
annotations.
Once they used at parameter level, violations are available via method-injected
Errors
BindingResult
type implementations.
ConstraintViolationException
is thrown each time an entity in non-valid state is passed to.save()
or.persist()
Hibernate methods.Entities may be manually validated via injected
LocalValidatorFactoryBean.validate()
method. The constraint violations then available through passedErrors
object's implementation.
Exactly, how@Valid
@Validated
annotations are internally implemented.
add a comment |
There're 3 ways:
@Valid
@Validated
annotations.
Once they used at parameter level, violations are available via method-injected
Errors
BindingResult
type implementations.
ConstraintViolationException
is thrown each time an entity in non-valid state is passed to.save()
or.persist()
Hibernate methods.Entities may be manually validated via injected
LocalValidatorFactoryBean.validate()
method. The constraint violations then available through passedErrors
object's implementation.
Exactly, how@Valid
@Validated
annotations are internally implemented.
There're 3 ways:
@Valid
@Validated
annotations.
Once they used at parameter level, violations are available via method-injected
Errors
BindingResult
type implementations.
ConstraintViolationException
is thrown each time an entity in non-valid state is passed to.save()
or.persist()
Hibernate methods.Entities may be manually validated via injected
LocalValidatorFactoryBean.validate()
method. The constraint violations then available through passedErrors
object's implementation.
Exactly, how@Valid
@Validated
annotations are internally implemented.
answered Nov 21 '18 at 19:17
WildDev
1,07731949
1,07731949
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
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