Mysql + Mybatis动态建表

service层业务

package com.zx.common.service.impl;

import com.zx.common.entity.SysUser;
import com.zx.common.mapper.SysUserMapper;
import com.zx.common.service.SysUserService;
import com.zx.common.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.UUID;

@Service("sysUserService")
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public List selectAllUser() {
        return sysUserMapper.selectAllUser();
    }

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public void updateUserInfoTimer() {
        //根据上一天的日期将sys_user重命名为sys_user_上一天日期

        String beforeDateStr = DateUtil.getBeforeDateString();
        String rename = "sys_user_" + beforeDateStr + UUID.randomUUID().toString().substring(0,16);
        sysUserMapper.renameTable(rename.replace("-",""));
        //新建sys_user表
        sysUserMapper.createTable();
    }
}

  mapper层接口

package com.zx.common.mapper;

import com.zx.common.entity.SysUser;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface SysUserMapper {

    List selectAllUser();

    void renameTable(@Param("tableName") String tableName);

    void createTable();
}

  mapper.xml




  
    
    
    
  
  
    ID, USERNAME, PASSWORD
  
  
      rename table sys_user to ${tableName };
  
  
    CREATE TABLE sys_user (
        ID INT(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
        USERNAME VARCHAR(64) NOT NULL DEFAULT '',
        PASSWORD VARCHAR(32) NOT NULL DEFAULT '',
        PRIMARY KEY(ID),
        KEY I_SYS_USER_USERNAME (USERNAME)
    )ENGINE=INNODB DEFAULT CHARSET=UTF8 COMMENT='用户表';
  


  

转载于:https://www.cnblogs.com/ningJJ/p/9185810.html

你可能感兴趣的:(Mysql + Mybatis动态建表)