title: Hibernate field length validation on SET methods
body: <p>Is there an easy way to have Hibernate validate field length constraints in the set() methods for each property?</p>
  
  <p><strong>I want to prevent the fields from EVER containing invalid values instead of waiting for Exceptions to occur later.</strong></p>
  
  <p>I have a class with a Username property:</p>
  
  <pre><code>@Column(name = "username", length = 12)
  public String getUsername()
  {
      return this.username;
  }
  
  public void setUsername(String username)
  {
      this.username = username;
  }
  </code></pre>
  
  <p>I can modify my Hibernate templates to create the set() methods this way:</p>
  
  <pre><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 &amp;&amp; username.length() &gt; maxLen)
          throw Exception("Username must be no more than " + maxLen + " characters.");
  
      this.username = username;
  }
  </code></pre>
  
  <p>Before I do this, I am wondering if there is some other approaches.</p>