Hibernate Naming Strategies

Using Hibernate annotations with the default naming strategy leaves you with camelCasedColumnNames in your database schema.

Gavin King provided a good camelCase to underscore_separated naming strategy with org.hibernate.cfg.ImprovedNamingStrategy. The only glitch I found was in foreign key references. I’ve always seen the naming convention of ${tablename}_id, but ImprovedNamingStrategy just called the column the same name as any other field. That’s easily overridden in a subclass:

public class NewAndImprovedNamingStrategy extends ImprovedNamingStrategy {
    @Override
    public String foreignKeyColumnName(String propertyName, String propertyEntityName, String propertyTableName, String referencedColumnName) {
        String s = super.foreignKeyColumnName(propertyName, propertyEntityName, propertyTableName, referencedColumnName);
        return s.endsWith("_id") ? s : s + "_id";
    }
}

If you’re using Spring, wire it up to your SessionFactoryBean:

  <bean id="namingStrategy" class="...NewAndImprovedNamingStrategy"/>
  ...
  <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="namingStrategy" ref="namingStrategy"/>
    ...

And you’ll be freed from doing boilerplate “name=” attributes in your domain POJOs.

Related posts:

  1. Simple spring integration testing
    Spring has had a really nice unit test framework available for a while now, but the documentation can be a bit daunting. Here’s a super-simple example of adding dependency injection......
  2. TestNG, test groups, IDEA, and @BeforeMethod
    Say you have public class SomeTestNG { @BeforeClass public void setup() { … } @Test public void test1() { … } @Test public void test2() { … } } You’ll......

This entry was posted in Technical HOWTOs and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

Additional comments powered by BackType