Saturday, 28 September 2013

Implementing Naming Convention in Hibernate

Quite offer we came across the case  where we have all the database tables and column follows a naming convention
For Example, All the table begins with a prefix of F_ and all column has a suffix of "_C".

If we want to implement this in hibernate, one solution would be to manually specify this in all mapping file of hibernate. How ever this approach is quite time consuming and easily forgotten over time when some new feature needs to be added at later .

Luckily Hibernate has some feature which enforces us to use this naming convention.
you can implement hibernate's NamingStrategy interface.

We extend ImprovedNamingStrategy which provides default implementation for all the methods of NamingStrategy interface which we don't want to implement.


package com.demo.example1;

import org.hibernate.cfg.ImprovedNamingStrategy;
import org.hibernate.util.StringHelper;

public class CustomNamingStratergy extends ImprovedNamingStrategy  {
@Override
public String classToTableName(String className){
return StringHelper.unqualify(className);
}
@Override
public String propertyToColumnName(String propertyName) {
        return propertyName;
}
@Override
public String tableName(String tableName) {
        return "F_" + tableName;
}
@Override
public String columnName(String columnName) {
        return columnName + "_C";
}

public String propertyToTableName(String className,
            String propertyName){

return "CE_"
        + classToTableName(className)
        + '_'
        + propertyToColumnName(propertyName);
}
}


Points to Note :

  1. classToTableName() method is called only when class mapping doesn't have an explicit table name
  2. propertyToColumnName() method is called only when property element doesn't have an explicit column name.
  3. tableName() and columnName() is called when we have declared  table name and column name.


So now, if we enable this CustomNamingStratergy , the class mapping decleration

<class name='person' table='person'>

results in F_person as the name of table and

<property name='firstName' column='first_name'>

would results in column name to be "first_name_c"

In order to activate the naming strategy, we need to pass an instance of the hibernate configuration at the startup.

Configuration cfg =new Configuration();
cfg.setNamingStrategy(new CustomNamingStratergy());
sessionFactory = cfg.configure("com/demo/example1/hibernate.cfg.xml").buildSessionFactory();

This allows us to have multiple sessionFactory instance to have different naming convention.



1 comment:

  1. Borgata Hotel Casino & Spa - Mapyro
    The Borgata Hotel Casino & Spa is a hotel on the waterfront in Atlantic 안성 출장마사지 City, NJ. It 제주 출장안마 has 42 floors and is connected to a full-service 영주 출장마사지 spa, four 경상북도 출장마사지 dining  Rating: 당진 출장안마 4.5 · ‎979 reviews

    ReplyDelete