Question

My table has column as char(5) and can not change it to varchar(5). So when I fetch values out from the table using hibernateTemplate , that returns added spaces with actual say single alphabet value.(A custome fix is to use .trim() method with checking NPE) but do we have a provided approach to handle this kind of situation. PS.I am using Spring support for hibernate dao support. (In SQL, the CHAR data type is a fixed length character string. By definition, the additional characters are padded wtih spaces.)

Was it helpful?

Solution 2

I have referred discussion on similar question here

Of the suggested solutions I feel adding user type best suites the requirements and makes more sense because 1. @PostLoad (Or actually lifecycle methods) does not work with using SessionFactory with hibernate. 2. Modification in assessor could be ignored during code refractor and another developer may overlook the setters which may lead to overwriting the setter.

So I am using following solution. 1.Have one package-info.java :- This has details for typedefs being used. 2.Annotated the fields with @Type(type="MyTrimTypeString") 3.Defined a user type class MyTrimTypeString, Code for which followed reply by StepherSwensen with a slight update on nullSafeGet looks like

 @Override
  public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException
  {
    final String val = rs.getString(names[0]);
    return (val == null ? val : val.trim());
  }

and nullSafeSet looks like :

@Override
  public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException
  {
    final String val = (String)value;
    st.setString(index, val);
  }

OTHER TIPS

One way of avoiding explicit call to trim() is you can provide a lifecycle method using a @PostLoad annotation n your Enitity. eg:

@PostLoad
protected void trim(){
    if(stringAttr!=null){
        stringAttr=stringAttr.trim();
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top