问题
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