Hibernate: Data Object with a dynamic table name by Annotations

Another one Architecture, more complez but elegant:

YES, You can change the table names using NamingStrategies:

public class MyNamingStrategy extends DefaultNamingStrategy {
   ...
   @Override
   public  String tableName(String tableName) {
      return tableName+yearSuffixTable;
   }
   ...
}

And, when you wanna to use the _year tables, you must to create a session with Hibernate that override rhe table names:

  SessionFactory sessionFactory;
  Configuration config = new AnnotationConfiguration()
                         .configure("hibernate.cfg.xml")
                         .setNamingStrategy( new MyNamingStrategy () );
  sessionFactory = config.buildSessionFactory();
  session = sessionFactory.openSession();

For my architecture I create a session by year and store it into Application map for access when I need it.

Thanks.

Leave a Comment