【hibernate】hibernate按月分表

 真是查了好久的资料,思路就是要做拦截器,这篇博文,但是保存时需要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();

        }

    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值