-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 1 post ] 
Author Message
 Post subject: Hibernate field length validation on SET methods
PostPosted: Thu Oct 18, 2012 6:14 pm 
Newbie

Joined: Thu Oct 18, 2012 6:07 pm
Posts: 3
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.


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 1 post ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.