最近发现HIBERNATE可以动态更换表名,真不简单,下面把原代码贴出来供参考:
public class ReportDBApi {
private SessionFactory sessionFactory = null;
public ReportDBApi(){
createSession();
}
public void createSession(){
Date date = new Date();
SimpleDateFormat simpledateformat = new SimpleDateFormat("yyyyMMdd");
String now_time = simpledateformat.format(date);
String tablename = "TBL_REPORT_STATUS_20050707";
tablename = "TBL_REPORT_STATUS_" + now_time;
try {
Configuration cfg = new Configuration().addClass(cn.sports.vas.sms.unicom.TblReportStatus.class).configure();
Table table = cfg.getClassMapping(TblReportStatus.class).getTable();
table.setName(tablename);
cfg.getClassMapping(TblReportStatus.class).setTable(table);
sessionFactory = cfg.buildSessionFactory();
}
catch (MappingException ex) {
ex.printStackTrace();
}catch (HibernateException ex) {
ex.printStackTrace();
}
}
public void insertPO(TblReportStatus po) throws HibernateException {
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.save(po);
tx.commit();
session.close();
}
public void closeSession() throws HibernateException {
sessionFactory.close();
}
}
这个类是每天新建一张表,并往里写数据。
博客介绍了Hibernate可动态更换表名的功能,并给出原代码。代码实现了每天新建一张表并写入数据,通过获取当前日期生成表名,利用Configuration类配置并构建SessionFactory,最后完成数据插入操作。

3412

被折叠的 条评论
为什么被折叠?



