Donation

If you found the contents in this blog useful, then please make a donation to keep this blog running. You can make donations via Skrill with email address shazin.sadakath@gmail.com

Friday, February 28, 2014

Custom Hibernate NamingStrategy

As part of my work my lead asked me to find a way to dynamically pre-pend a prefix to all the Hibernate Entities which uses JPA @Entity Annotation. This is to create a way to implement a flexible, customizable way to generate Entities which can be used across different projects by just changing the prefix.

So after some googling I found a link [1] where it is explained how to use a Custom NamingStrategy but it didn't quite do the exact my lead was looking for because it worked only with @Entity annotated classes which do not have @Table annotation. But my lead wanted to keep the @Table annotation and he wanted the @JoinTable annotation names also to be prefixed.

So after some trial and error I came up with the following changes with a Custom implementation of org.hibernate.cfg.ImprovedNamingStrategy and one hibernate configuration.

import org.hibernate.cfg.ImprovedNamingStrategy;

public class CustomNamingStrategy extends ImprovedNamingStrategy {
    
    private String prefix = "customprefix_";
    
    public String tableName(String tableName) {
        return _prefix(super.tableName(tableName));
    }
    
    public void setPrefix(String prefix) {
        this.prefix = prefix;
    }
    
    private String _prefix(String table) {
        return prefix + table;
    }

}


and following configuration for hibernate

<prop key="hibernate.ejb.naming_strategy">CustomNamingStrategy</prop>

  1. http://www.petrikainulainen.net/programming/tips-and-tricks/implementing-a-custom-namingstrategy-with-hibernate/

No comments: