Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate: Data Object with a dynamic table name by Annotations

I have a Data Class for Hibernate associated to a table; imagine the Entity Person like this:

 @Entity
 @org.hibernate.annotations.Proxy(lazy=false)
 @Table(name="Person", schema="MySchema")
 @Inheritance(strategy=InheritanceType.SINGLE_TABLE)
 public class ProfileData implements Serializable {

    private static final long serialVersionUID = -844564646821609090L;

    public PersonData() {
    }

    @Column(name="idPerson", nullable=false, unique=true)   
    @Id 
    ...

I need to create historic tables by years of this table: Person2010, Person2011, Person2012... Is it possible without creating new Data Objects? Maybe by a parameter...? I don´t know.

The Entity class is the same, changing the table name and the constructor.

like image 207
ganzux Avatar asked Dec 20 '11 09:12

ganzux


2 Answers

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.

like image 168
ganzux Avatar answered Nov 15 '22 15:11

ganzux


You should try Hibernate Envers for historic data.

like image 21
tobiasbayer Avatar answered Nov 15 '22 17:11

tobiasbayer