Hibernate动态切换表
2013-05-12 19:35 阅读(193)


最近发现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();
  }
}


这个类是每天新建一张表,并往里写数据。


来自:http://blog.csdn.net/jljf_hh/archive/2005/07/14/424510.aspx