0

I want to ask how to handle uniquecontraint exception at thymeleaf. To handle excpetion I am using this:

<span th:style="'color:red'" th:if="${#fields.hasErrors('userName')}" th:errors="*{userName}">Name Error</span>

It handles lenght exception and not null, but why it fail with uniqe constraint, my entity looks like this:

@Entity(name = "Users")
@Table(
        name = "\"users\"",
        uniqueConstraints = {
                @UniqueConstraint( name = "users_username_unique", columnNames = "user_name")
        }
)
public class Users {

...

    @Column(
            name = "user_name",
            nullable = false,
            columnDefinition = "TEXT",
            updatable = false
    )
    @Length(min = 5, message = "*User name is too short")
    @NotEmpty(message = "*Enter user name")
    private String userName;

...
}

1 Answers1

1

Unique columns will be used only in DDL generation, it doesn't have any impact during runtime. The actual uniqueness checks happens in the database.

I can suggest method for you to do this. The method is to check if this username is available and you can make an error accordingly, s an example, it could be a code like this:

Optional<Users> optionalUser = userRepository.findByUserName(..);
if(optionalUser.isPresent()){
    bindingResult.rejectValue("userName", "error.userName", "You cannot use this username!");
    return "form";
}

More information about the BindingResult class and the rejectValue() method, see here: https://stackoverflow.com/a/65759773/2039546

OR

Other of the possible solutions is to create custom annotation and validator, see here: https://stackoverflow.com/a/4733441/2039546

İsmail Y.
  • 3,579
  • 5
  • 21
  • 29