Is there an easy way to have Hibernate validate field length constraints in the set() methods for each property?
I want to prevent the fields from EVER containing invalid values instead of waiting for Exceptions to occur later (at Runtime).I have a class with a Username property:
Code:
@Column(name = "username", length = 12)
public String getUsername()
{
return this.username;
}
public void setUsername(String username)
{
this.username = username;
}
I can modify my Hibernate templates to create the set() methods this way:
Code:
@Column(name = "username", length = 12)
public String getUsername()
{
return this.username;
}
public void setUsername(String username)
{
Method m = ClassWithUsername.getDeclaredMethod("setUsername");
javax.persistence.Column col = m.getAnnotation(javax.persistence.Column.class);
int maxLen = col.length();
// Validate the field length
if(username!=null && username.length() > maxLen)
throw Exception("Username must be no more than " + maxLen + " characters.");
this.username = username;
}
Before I do this, I am wondering if there are some other/better approaches.