Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lowercase annotation in Hibernate

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.

like image 657
Eugene Stepanenkov Avatar asked Jan 16 '23 05:01

Eugene Stepanenkov


2 Answers

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/

like image 82
Roman Makhlin Avatar answered Jan 24 '23 12:01

Roman Makhlin


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;  
}
like image 26
Ilya Avatar answered Jan 24 '23 13:01

Ilya