Is there any way in hibernate to annotate the column of the entity to string lowercase? I mean for example
@Entity
public class User {
@Column
private String username;
}
I want the hibernate to convert the username to lowercase in all queries not tied to a specific database.
You can, for example, make it in setter:
public void setUsername(String username) {
this.username = username.toLowerCase();
}
Or use interseptor:
public boolean onSave(Object entity,Serializable id, Object[] state,String[] propertyNames,Type[] types) throws CallbackException {
if (entity instanceof User ){
entity.username = usename.toLowerCase();
}
return false;
}
you can read more about intercepters here: http://www.mkyong.com/hibernate/hibernate-interceptor-example-audit-log/
You can write your own UserType
for this string
public class LowerCaseString implements UserType
{
//....
public void nullSafeSet(PreparedStatement preparedStatement, Object value, int index)
throws HibernateException, SQLException {
Hibernate.STRING.nullSafeSet(preparedStatement,
(value != null) ? ((String)value).toLowerCase() : null, index);
}
///....
}
you entity
@Entity
public class User {
@Column
@Type(type="com.youcompany.LowerCaseString")
private String username;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With