Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Way to automatically truncate a String column using JPA / Spring / Hibernate?

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.

like image 401
Dave Avatar asked Nov 11 '13 16:11

Dave


1 Answers

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)
like image 196
Steve Avatar answered Oct 04 '22 11:10

Steve