Case-insensitive JPA unique constraint?

≡放荡痞女 提交于 2019-12-10 15:59:46

问题


I'm currently using

@Entity
public class ... {

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

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?


回答1:


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

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();
    }
}

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));


来源:https://stackoverflow.com/questions/22645618/case-insensitive-jpa-unique-constraint

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!