hibernate unique key validation

后端 未结 6 769
后悔当初
后悔当初 2020-12-23 22:36

I have a field, say, user_name, that should be unique in a table.

What is the best way for validating it using Spring/Hibernate validation?

6条回答
  •  既然无缘
    2020-12-23 23:28

    I've found kind of a tricky solution.

    First, I've implemented the unique contraint to my MySql database :

    CREATE TABLE XMLTAG
    (
        ID INTEGER NOT NULL AUTO_INCREMENT,
        LABEL VARCHAR(64) NOT NULL,
        XPATH VARCHAR(128),
        PRIMARY KEY (ID),
        UNIQUE UQ_XMLTAG_LABEL(LABEL)
    ) ;
    

    You see that I manage XML Tags that are defined by a unique label and a text field named "XPath".

    Anyway, the second step is to simply catch the error raised when the user tries to do a bad update. A bad update is when trying to replace the current label by an existing label. If you leave the label untouched, no problemo. So, in my controller :

        @RequestMapping(value = "/updatetag", method = RequestMethod.POST)
        public String updateTag(
                @ModelAttribute("tag") Tag tag, 
                @Valid Tag validTag,
                BindingResult result,
                ModelMap map) {
    
            if(result.hasErrors()) {        // you don't care : validation of other
                return "editTag";       // constraints like @NotEmpty
            }
            else {
                try {
                    tagService.updateTag(tag);    // try to update
                    return "redirect:/tags";   // <- if it works        
                }
                catch (DataIntegrityViolationException ex) { // if it doesn't work
                    result.rejectValue("label", "Unique.tag.label"); // pass an error message to the view 
                    return "editTag"; // same treatment as other validation errors
                }
            }
        }
    

    This may conflict with the @Unique pattern but you can use this dirty method to valid the adding too.

    Note : there is still one problem : if other validation errors are catched before the exception, the message about unicity will not be displayed.

提交回复
热议问题