Tuesday, January 22, 2008

Let Hibernate generate pluralized table names

On my little home project I am using annotations-based Hibernate persistence. As a personal preference I like table names to be pluralized (Call it Rails-inspired). Unfortunately, Hibernate does not provide any support for such a feature and therefore I always ended up specifying the table columns explicitly:

@Entity
@Table(name="jobs")
public class Job implements Serializable {


However, there are hooks to change the default Hibernate NamingStrategy implementation. This means, if you don't provide the @Table annotation then the class name maps directly to the table name.

In fact Hibernate comes with 2 naming strategy implementations out of the box:

Well, on Java.net I came across the Inflector project, which generates the plural of provided nouns. Using it could not be simpler:

String result = Noun.pluralOf(“cat”) ; // = cats

As a result of that find, I created my own class ImprovedPluralizedNamingStrategy which uses ImprovedNamingStrategy as a base. I refactored the contained method classToTableName() so that it returns a pluralized version of the class name.

Also, if you like to know more on how to configure Hibernate naming strategies when using Spring, check out this blog.

What I have done is certainly not production ready but it shows that adding your custom naming strategy to Hibernate is fairly easy to accomplish and helps reducing annotation clutter in my classes.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

Links to this post:

Create a Link

<< Home