In case anyone stubles accross this post with the same problem, my solution is:
Code:
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import net.sf.hibernate.type.StringType;
import net.sf.hibernate.util.StringHelper;
/**
* @author MarcWilson
*/
public abstract class TruncateStringType extends StringType
{
private static final Log log = LogFactory.getLog( StringHelper.qualifier( TruncateStringType.class.getName() ) );
public static class TruncateStringType5 extends TruncateStringType {}
public static class TruncateStringType50 extends TruncateStringType {}
public static class TruncateStringType100 extends TruncateStringType {}
public static class TruncateStringType200 extends TruncateStringType {}
private int length;
protected TruncateStringType()
{
this.length = getLength(getClass().getName());
}
private int getLength(String className)
{
int i = className.length();
while(Character.isDigit(className.charAt(i-1)))
{
i--;
}
return Integer.parseInt(className.substring(i));
}
Object truncate(String value)
{
if(value != null && value.length() > length)
{
log.warn("String value of length " + value.length() + " was truncated to length " + length + " to fit");
if(log.isDebugEnabled())
{
log.debug("Initial (untruncated) string:" + value);
}
value = value.substring(0, length);
}
return value;
}
public void set(PreparedStatement st, Object value, int index) throws SQLException
{
super.set(st, truncate((String)value), index);
}
}
which can be used like:
Code:
<property
name="response"
type="TruncateStringType$TruncateStringType200"
column="response"
length="200"
not-null="false"
unique="false"
/>
I extended StringType instead of implementing UserType, but I think I have achieved the same objective (although leaving it opens to problems from future changes in the StringType implementation).
The annoying part is u need to add another TruncateStringTypeXXXX class for every new length (XXXX) you want to be able to truncate to. This can be fixed if and when
HB-469 is implemented.