Thymeleaf 和@Uniqueconstraint [英] Thymeleaf and @Uniqueconstraint

查看:24
本文介绍了Thymeleaf 和@Uniqueconstraint的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想问一下如何处理 thymeleaf 的 uniquecontraint 异常.为了处理异常,我正在使用它:

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>

它处理 lenght 异常而不是 null,但为什么它会因 uniqe 约束而失败,我的实体看起来像这样:

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;

...
}

推荐答案

唯一列只会在DDL生成时使用,在运行时不会有任何影响. 实际的唯一性检查发生在数据库中.

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";
}

有关 BindingResult 类和 rejectValue() 方法的更多信息,请参见此处:https://stackoverflow.com/a/65759773/2039546

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

OR

其他可能的解决方案是创建自定义注释和验证器,请参见此处:https://stackoverflow.com/a/4733441/2039546

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

这篇关于Thymeleaf 和@Uniqueconstraint的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆