真是查了好久的资料,思路就是要做拦截器,这篇博文,但是保存时需要openSession,不能使用getCurrentSession,事务不被spring管理。
又查了半天,拦截器的升级版,链接找不到了,大概思路就是在需要修改表名时,注入sessionFactory创建session,用了sessionBuilder之类的,但是那个类是hibernate4.1.4之后的.....公司用的是hibernate3,无奈方法又作废。
最终解决方案,使用 SQLQuery来直接执行sql语句。
https://hollyshi.github.io/2014/11/02/hibernate-mapping-dealing-with-one-class-to-many-tables
@Transactional(rollbackFor=Exception.class)
public void insertArcCopy(Arc arc){
Calendar ca = Calendar.getInstance();
ca.setTime(arc.getStartTime());
//获取
int year = ca.get(Calendar.YEAR);
int month = ca.get(Calendar.MONTH) + 1;
String monthString=year+""+month;
if(month<10){
monthString=year+"0"+month;
}
//判断表是否存在,不存在则创建
String sqlExist = "select * from information_schema.tables where table_name = 'ARC_95013_"+monthString+"'";
SQLQuery queryExist = this.getSession().createSQLQuery(sqlExist);
int count = queryExist.list().size();
Boolean result=false;
if(count > 0){result=true;}
if(result){
String sql = "insert into ARC_"
+ monthString
+ " (call_id,unitid) values (?,?)";
Session session=this.getSession();
SQLQuery query = session.createSQLQuery(sql);
query.setString(0, "insert"+ UUID.randomUUID());
query.setString(1, arc95013.getUnitid());
query.executeUpdate();
}else{
String sql = "CREATE TABLE ARC_"+monthString+" (\n" +
" `id` bigint(20) NOT NULL AUTO_INCREMENT,\n" +
" `CALL_ID` varchar(255) NOT NULL,\n" +
" `UNITID` varchar(16) DEFAULT NULL,\n" +
" PRIMARY KEY (`id`),\n" +
" UNIQUE KEY `CALL_ID` (`CALL_ID`)\n" +
") ENGINE=InnoDB DEFAULT CHARSET=utf8;";
Session session=this.getSession();
SQLQuery query = session.createSQLQuery(sql);
query.executeUpdate();
//插入数据
String sqlInsert = "insert into ARC_"
+ monthString
+ " (call_id,unitid) values (?,?)";
SQLQuery queryInsert = this.getSession().createSQLQuery(sqlInsert);
queryInsert.setString(0, "123456"+ UUID.randomUUID());
queryInsert.setString(1, "654321");
queryInsert.executeUpdate();
}
}