不区分大小写的JPA唯一约束

不区分大小写的JPA唯一约束

本文介绍了不区分大小写的JPA唯一约束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当前正在使用

@Entity
public class ... {

    /**
     * @return the loginName
     */
    @Column(unique=true)
    public String getLoginName() {
        return loginName;
    }

但是喜欢具有不区分大小写的约束,因此,如果数据库中已经存在登录名大写",则不允许登录名"UPPERCASE".我有什么可以使用的,还是必须创建一种肮脏的解决方法,将小写版本存储在单独的列中?

but like to have a case-insensitive constraint such that a login name "UPPERCASE" is not allowed when there is already a login name "uppercase" in the database. Is there anything I can use or do I have to create the dirty workaround of storing a lower case version in a separate column?

推荐答案

这不是JPA所涵盖的,我什至不会说实现(例如Hibernate).

This is not something covered by JPA, and I'd say not even implementations (e.g. Hibernate).

您可以做的一件事是创建一个 @PrePersist@PreUpdate处理程序,它们将使用规范化的(小写)值填充另一个(附加)实体字段,并对此施加约束.

One thing you can do is create a @PrePersist and @PreUpdate handler that will fill another (additional) entity field with normalized (lowercase) value, and have the constraint on that.

@Entity Foo {
    private value;
    @Column(unique = true)
    private valueLowercased;

    @PrePersist @PreUpdate private prepare(){
        this.valueLowercased = value == null ? null : value.toLowerCase();
    }
}

非JPA方法可能是在具有UNIQUE INDEX的附加列myColumnLowercased和将值设置为LOWERCASE(new.myColumn)的触发器. (各数据库的名称可能有所不同.)

Non-JPA approach could be to have an additional column myColumnLowercased with an UNIQUE INDEX and a trigger that would set the value to LOWERCASE(new.myColumn). (Nomenclature may differ across databases.)

某些数据库支持功能索引" ,即您可以按表达式编制索引.

Some databases support "functional indexes" which is you can index by an expression.

CREATE INDEX test1_lower_col1_idx ON test1 (lower(col1));

这篇关于不区分大小写的JPA唯一约束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-27 21:08