I'm using Spring 3.1.1.RELEASE, JPA 2.0, and Hibernate 4.1.0.Final. I have a MySQL 5.5 column of VARCHAR(100) type. If I save an entity whose value is larger than 100 characters, unsurprisingly, the save fails with the error
SQL [n/a]; nested exception is org.hibernate.exception.DataException: Data truncation: Data too long for column 'MY_COL' at row 1
org.springframework.dao.DataIntegrityViolationException: Data truncation: Data too long for column
Is there a way to set Spring/Hibernate/JPA so that if my String value is too long, the data will be automatically truncated to the maximum length? I realize I could add code to automatically check if the String is 100 characters and then truncate the String with Java, but I wa curious if there's a less rigorous way to do this.
Is there a reason why you wouldn't just put the truncation in your setString(String) method? It would appear that you have a domain rule that it shoudl always be truncated at 100 chars, so enforce it:
public void setName(String name) {
this.name = name.length() > 100 ? name.substring(0,100) : name;
}
If that looks too difficult and verbose, and you do this all the time, why not use Spring AOP and create your own annotation?
@Truncate(length=100)
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