Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8610517
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 12, 20262026-06-12T04:09:01+00:00 2026-06-12T04:09:01+00:00

We all know, that Spring MVC integrate well with Hibernate Validator and JSR-303 in

  • 0

We all know, that Spring MVC integrate well with Hibernate Validator and JSR-303 in general. But Hibernate Validator, as someone said, is something for Bean Validation only, which means that more complex validations should be pushed to the data layer. Examples of such validations: business key uniqueness, intra-records dependence (which is usually something pointing at DB design problems, but we all live in an imperfect world). Even simple validations like string field length may be driven by some DB value, which makes Hibernate Validator unusable.

So my question is, is there something Spring or Hibernate or JSR offers to perform such complex validations? Is there some established pattern or technology piece to perform such a validation in a standard Controller-Service-Repository setup based on Spring and Hibernate?

UPDATE: Let me be more specific. For example, there’s a form which sends an AJAX save request to the controller’s save method. If some validation error occurs — either simple or “complex” — we should get back to the browser with some json indicating a problematic field and associated error. For simple errors I can extract the field (if any) and error message from BindingResult. What infrastructure (maybe specific, not ad-hoc exceptions?) would you propose for “complex” errors? Using exception handler doesn’t seem like a good idea to me, because separating single process of validation between save method and @ExceptionHandler makes things intricate. Currently I use some ad-hoc exception (like, ValidationException):

public @ResponseBody Result save(@Valid Entity entity, BindingResult errors) {
    Result r = new Result();
    if (errors.hasErrors()) {
        r.setStatus(Result.VALIDATION_ERROR);     
        // ...   
    } else {
        try {
            dao.save(entity);
            r.setStatus(Result.SUCCESS);
        } except (ValidationException e) {
            r.setStatus(Result.VALIDATION_ERROR);
            r.setText(e.getMessage());
        }
    }
    return r;
}

Can you offer some more optimal approach?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-12T04:09:02+00:00Added an answer on June 12, 2026 at 4:09 am

    Yes, there is the good old established Java pattern of Exception throwing.
    Spring MVC integrates it pretty well (for code examples, you can directly skip to the second part of my answer).

    What you call "complex validations" are in fact exceptions : business key unicity error, low layer or DB errors, etc.


    Reminder : what is validation in Spring MVC ?

    Validation should happen on the presentation layer. It is basically about validating submitted form fields.

    We could classify them into two kinds :

    1) Light validation (with JSR-303/Hibernate validation) : checking that a submitted field has a given @Size/@Length, that it is @NotNull or @NotEmpty/@NotBlank, checking that it has an @Email format, etc.

    2) Heavy validation, or complex validation are more about particular cases of field validations, such as cross-field validation :

    • Example 1 : The form has fieldA, fieldB and fieldC. Individually, each field can be empty, but at least one of them must not be empty.
    • Example 2 : if userAge field has a value under 18, responsibleUser field must not be null and responsibleUser‘s age must be over 21.

    These validations can be implemented with Spring Validator implementations, or custom annotations/constraints.

    Now I understand that with all these validation facilites, plus the fact that Spring is not intrusive at all and lets you do anything you want (for better or for worse), one can be tempted to use the "validation hammer" for anything vaguely related to error handling.
    And it would work : with validation only, you check every possible problem in your validators/annotations (and hardly throw any exception in lower layers). It is bad, because you pray that you thought about all the cases. You don’t leverage Java exceptions that would allow you to simplify your logic and reduce the chance of making a mistake by forgetting to check that something had an error.

    So in the Spring MVC world, one should not mistake validation (that is to say, UI validation) for lower layer exceptions, such has Service exceptions or DB exceptions (key unicity, etc.).


    How to handle exceptions in Spring MVC in a handy way ?

    Some people think "Oh god, so in my controller I would have to check all possible checked exceptions one by one, and think about a message error for each of them ? NO WAY !". I am one of those people. 🙂

    For most of the cases, just use some generic checked exception class that all your exceptions would extend. Then simply handle it in your Spring MVC controller with @ExceptionHandler and a generic error message.

    Code example :

    public class MyAppTechnicalException extends Exception { ... }
    

    and

    @Controller
    public class MyController {
    
        ...
    
        @RequestMapping(...)
        public void createMyObject(...) throws MyAppTechnicalException {
            ...
            someServiceThanCanThrowMyAppTechnicalException.create(...);
            ...
        }
    
        ...
    
        @ExceptionHandler(MyAppTechnicalException.class)
        public String handleMyAppTechnicalException(MyAppTechnicalException e, Model model) {
    
            // Compute your generic error message/code with e.
            // Or just use a generic error/code, in which case you can remove e from the parameters
            String genericErrorMessage = "Some technical exception has occured blah blah blah" ;
    
            // There are many other ways to pass an error to the view, but you get the idea
            model.addAttribute("myErrors", genericErrorMessage);
    
            return "myView";
        }
    
    }
    

    Simple, quick, easy and clean !

    For those times when you need to display error messages for some specific exceptions, or when you cannot have a generic top-level exception because of a poorly designed legacy system you cannot modify, just add other @ExceptionHandlers.
    Another trick : for less cluttered code, you can process multiple exceptions with

    @ExceptionHandler({MyException1.class, MyException2.class, ...})
    public String yourMethod(Exception e, Model model) {
        ...
    }
    

    Bottom line : when to use validation ? when to use exceptions ?

    • Errors from the UI = validation = validation facilities (JSR-303 annotations, custom annotations, Spring validator)
    • Errors from lower layers = exceptions

    When I say "Errors from the UI", I mean "the user entered something wrong in his form".

    References :

    • Passing errors back to the view from the service layer
    • Very informative blog post about bean validation
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have an application built on Spring MVC that uses Hibernate for all of
First, let me explain that I'm using Spring MVC 3.1.1, and Hibernate validation 4.2.0.
We all know that openId has become such a popular method for user authentication,
We all know that CSS sprite images are great to reduce the amount of
We all know that a hash table has O(1) time for both inserts and
We all know that most applications out there assume class names to follow the
as you all know that if we use flash object in web page in
as we all know that html_safe work in controller and view i am sending
So we all know that when iterating through a PHP array using foreach, the
As you all might know that the MIPS instruction set supports clz (count leading

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.