Hibernate: Data Object with a dynamic table name by Annotations

后端 未结 6 853
抹茶落季
抹茶落季 2020-12-09 13:06

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

 @Entity
 @org.hibernate.annotations.Proxy(lazy=false)         


        
相关标签:
6条回答
  • 2020-12-09 13:08
    @Table(name="emd_employee_1001")
    

    In the above annotation file name can pass as parameter, for example

    x=1001 
    @Table(name="emd_employee_+x+")
    
    0 讨论(0)
  • 2020-12-09 13:08

    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();
    
    0 讨论(0)
  • 2020-12-09 13:10

    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:

    • _AUD TABLE is renamed as _PAST_YEAR table.
    • A new _AUD table is created.
    • A new hibernate.cfg.past_year.xml is created with the new suffix.

    When I need to get data, I load the corresponding hibernate configuration file.

    Hope this helps to others :)

    0 讨论(0)
  • 2020-12-09 13:11

    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.

    0 讨论(0)
  • 2020-12-09 13:19

    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).

    0 讨论(0)
  • 2020-12-09 13:31

    You should try Hibernate Envers for historic data.

    0 讨论(0)
提交回复
热议问题