---
title: "Hibernate 动态表名"
author: "hwpok"
date: "2009-07-16T23:20:00Z"
tags: []
slug: "hibernate"
draft: false
lastmod: "2009-07-16T23:20:00Z"
id: 615751
url: "https://hwpok.iteye.com/blog/615751"
---

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

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

 

本文来自CSDN博客，转载请标明出处：http://blog.csdn.net/jljf\_hh/archive/2005/07/14/424510.aspx