I have an entity where I set the max
for every String field like the following:
@Column(name = "abc")
@Size(max = 10)
private String abc;
@Column(name = "xyz")
@Size(max = 50)
private String xyz;
I want to write a Converter to truncate that field if exceeds max size. Something like this:
import javax.persistence.AttributeConverter;
import javax.persistence.Convert;
@Convert
public class TruncatedStringConverter implements AttributeConverter<String, String> {
private static final int LIMIT = 999;
@Override
public String convertToDatabaseColumn(String attribute) {
if (attribute == null) {
return null;
} else if (attribute.length() > LIMIT) {
return attribute.substring(0, LIMIT);
} else {
return attribute;
}
}
@Override
public String convertToEntityAttribute(String dbData) {
return dbData;
}
}
But the thing is that I can't use LIMIT
since I need to look to the Size annotation. Is there any way to access the field name from the converter?
This way I could use reflection to read the max size.
Thank you!