Search code examples
springthymeleaf

Thymeleaf - Verify if preperty already exists


Basically my question is very simple, I have a registration form with a constraint on field "login".

Table(uniqueConstraints=@UniqueConstraint(columnNames = { "login" }))

So, when I add a login which is already exists, an exception shows up: Duplicate entry 'MyLogin' for key 'UKew1hvam8uwaknuaellwhqchhb'.

I'm asking if there's any way in thymeleaf to just show a message saying that name already exists.


Solution

  • I would check if user already exists in table with the same username(I think your "login" is same as username for the user) before making any persistence transaction for new user, if username already exists in the table simply do not go forward and execute new user registration logic and let form controller return view with the Model object with the duplicate username attribute returned by service method.(you can use exceptions in service methods for better logic)

    @RequestMapping("/registerNewUser")
    public String showModel(@ModelAttribute UserDataTransferObject userDTO, Model model){
    
    
        String existedUsername = service.createUser(userDTO);
        if(existedUsername != null){
            model.addAttribute("existedUsername",existedUsername);
        }
    
        return "registrationstatus";
    
    }
    

    createUser method checks if repository contains entry with the same username and if so returns that username as a string (Simple implementation).

    in thymeleaf:

    <div th:if="${existedUsername != null}" class="alert alert-danger notification" role="alert">
       <p th:text="${existedUsername}"></p><p> already exists</p>
    </div>