Posts tagged annotations
Hibernate Naming Strategies
Apr 12th
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.