MyBatis动态创建表格,并且复制数据

一 业务要求

老师交代任务,数据库有一张表,现在需要前端页面在条件搜索下得到的数据,保存在另一张表中,这表是动态生成的,但是新表的结构和源表结构一样,项目框架使用的MyBatis,这里面有两个操作:

  1. 动态生成表
  2. 复制条件查询的数据到新表中
  3. 检验新表生成是否重复

二 代码实现

1.通过MyBatis插件生成DAO层,XML,POJO类
图片说明
2.检验该动态是否存在,如果存在,会删除,重新建的

 <select id="isTableExist" parameterType="java.lang.String" resultType="java.lang.Integer">
        select count(*) from information_schema.TABLES where table_name = #{tableName}
    </select>

3.动态生成表格

<update id="addNewTable">
      create table ${tableName} like t_imsirpt;
    </update>

4.复制数据

 <insert id="copyOf" parameterType="com.nkr.ndp.dao.bean.TImsirpt">
        insert into ${tableName}
        select * from t_imsirpt i
        where 1=1
        <if test="devices !=null and  devices.length > 0">
            and devid in
            <foreach collection="devices" item="item" index="index"
                     open="(" close=")" separator=",">
                #{item}
            </foreach>
        </if>
        <if test=" imsi!=null and imsi!=0L">
            and imsi like "%"#{imsi}"%"
        </if>
        <if test=" isdn!=null and isdn!='' ">
            and isdn like "%"#{isdn}"%"
        </if>
        <if test="beginTime !=null ">
            <![CDATA[ and time  >=  #{beginTime}  ]]>
        </if>
        <if test="endTime !=null ">
            <![CDATA[ and time <  #{endTime}  ]]>
        </if>
    </insert>

5.DAO层接口

 //检查表是否存在
    int isTableExist(@Param("tableName") String tableName);

    //动态创建表格
    int addNewTable(@Param("tableName") String tableName);

    //复制数据
    int copyOf(@Param("tableName") String tableName,
               @Param("devices") String[] devices,
               @Param("beginTime") Date beginTime,
               @Param("endTime") Date endTime,
               @Param("imsi") Long imsi,
               @Param("isdn") String isdn);

总结

1.这只是应对两个不同表但是数据结构是一样,其实不一样,原理也是一样
2.数据量过大的时候,建议合并添加和复制两个语句,可提高效率,但是校验一层就不存在了
3.表明不能重复,一旦重复,上次查询的结果就会被覆盖