問題描述
我有一個與表關聯的 Hibernate 數據類;想象像這樣的實體Person:
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
...
我需要按此表的年份創建歷史表:Person2010、Person2011、Person2012... 是否可以不創建新的數據對象?也許通過參數...?我不知道.
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.
Entity類是一樣的,表名和構造函數都變了.
The Entity class is the same, changing the table name and the constructor.
推薦答案
另一種架構,更復雜但優雅:
Another one Architecture, more complez but elegant:
YES,您可以使用 NamingStrategies 更改表名:
YES, You can change the table names using NamingStrategies:
public class MyNamingStrategy extends DefaultNamingStrategy {
...
@Override
public String tableName(String tableName) {
return tableName+yearSuffixTable;
}
...
}
而且,當您想使用 _year 表時,您必須使用 Hibernate 創建一個覆蓋 rhe 表名稱的會話:
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.
謝謝.
這篇關于Hibernate:通過注釋具有動態表名的數據對象的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!