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="emd_employee_1001")
In the above annotation file name can pass as parameter, for example
x=1001
@Table(name="emd_employee_+x+")
Modified at runtime(I think it's the best way):
Session session = super.getSession();
SQLQuery query = session.createSQLQuery("raw sql");
query.setParameter(":abc", "value");
query.addEntity(Some.class);
return query.list();
Thanks to @CodeBrickie and @edutesoy I found Envers.
I configure the hibernate config file with AUD suffix and I create new hibernate config files per year (hibernate.cfg.2009.xml, hibernate.cfg.2010.xml, hibernate.cfg.2011.xml...) with the year-suffix.
When I save data, always is audited in AUD table. On January 1, automatically:
When I need to get data, I load the corresponding hibernate configuration file.
Hope this helps to others :)
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.
In Hibernate you map 1 class to 1 table. You can not reuse the same Entity to map several tables dynamically.
Hibernate Envers is a quite good solution for Historic data, but you still will not be able to do what you try (dynamically grow the number of tables without touching mapper Entities).
You should try Hibernate Envers for historic data.