mysql动态建表+定时任务(二、java代码做定时任务,操作mysql数据库)

发布于:2022-12-24 ⋅ 阅读:(941) ⋅ 点赞:(0)

注:分两篇博客介绍下方三种自动定时建表方式。

1.直接操作mysql数据库

2.通过java代码定时操作mysql数据库,进行建表

3.存储过程写在mysql上,通过java代码设置定时任务调用存储过程。

希望对有同样困惑的人有帮助

一、通过java代码定时操作mysql数据库,进行建表

(1)新建一个springboot项目,代码结构如下图所示

 (2)在pom.xml文件中引入依赖

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.0</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
         <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
    
        </dependency>

(3)在springboot启动类上加入

@MapperScan(basePackages = "com.fxr.learnautocreatetable.mapper")

 (4)编写application.yml配置文件,配置定时任务,和配置数据库连接

task:
  switch:
    is-open: true #开关
  corn:
    task-corn: 0/2 47 16  07 * ?  #定时任务时间格式
spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/learn?serverTimezone=GMT%2B8&characterEncoding=UTF-8&useSSL=false
    driver-class-name: com.mysql.jdbc.Driver
    username: root
    password: "123456"

注:定时任务的时间格式在网上可以搜到

 

 (5)编写mybatis的CreateTableMapper.xml配置文件,动态创建table

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.fxr.learnautocreatetable.mapper.CreateTableMapper">
<update id="createTable" parameterType="java.lang.String">
CREATE TABLE `${tableName}` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `name` varchar(50) NOT NULL COMMENT '用户名',
  `phone` varchar(150) DEFAULT NULL COMMENT '手机号码',
  PRIMARY KEY (`id`),
  UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=34 DEFAULT CHARSET=utf8 COMMENT='用户信息';
</update>
</mapper>

(6)mapper接口

package com.fxr.learnautocreatetable.mapper;

import org.apache.ibatis.annotations.Param;

public interface CreateTableMapper {
    public void createTable(@Param("tableName") String tableName);
}

(7)service实现类

package com.fxr.learnautocreatetable.service;

import com.fxr.learnautocreatetable.mapper.CreateTableMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class CreateTableService {
    @Resource
    private CreateTableMapper createTableMapper;
    public void createTable(String tablName){
        createTableMapper.createTable(tablName);
    }
}

(8)定时任务类

package com.fxr.learnautocreatetable.task;

import com.fxr.learnautocreatetable.service.CreateTableService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

@Component
@EnableScheduling
public class AutoCreateTable {
    @Value("${task.switch.is-open}")
    private boolean flag;
    @Autowired
    private CreateTableService createTableService;
    @Scheduled(cron = "${task.corn.task-corn}")
    public void m1() {
        if (flag){
            SimpleDateFormat stf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = stf.format(new Date());
            System.out.println("定时任务启动->>" + format);
            createTableService.createTable(format);
        }else {
            System.out.println("未开启定时任务开关,请重试!");
        }
    }
}

(9)启动项目即可

二、通过java代码定时操作mysql数据库,调用存储过程

(1)项目结构同上

(2)编写存储过程

CREATE DEFINER=`root`@`localhost` PROCEDURE `test_create_table_by_auto`()
BEGIN
		set @stmtSql = concat(
	'CREATE TABLE IF NOT EXISTS log_', date_format(curdate(),'%y%m%d'),
	"(
		`stu_id` int(10) NOT NULL AUTO_INCREMENT,
		`telephone` int(11) NOT NULL, 
		`name` varchar(30) NOT NULL DEFAULT '',
		PRIMARY KEY (`stu_id`)
	) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8");
					#预定义sql语句,从用户变量中获取
					prepare stmt from @stmtSql;
					#执行sql语句
					execute stmt;
					#释放资源,后续还可以使用
					deallocate prepare stmt;
		
END

(3)在mybatis的CreateTableMapper.xml配置文件中编写语句,并在mapper中编写对应接口,及service编写方法进行调用,步骤同上不一一介绍了。

mybatis调用存储过程语句

{call test_create_table_by_auto()}

到此:自学的三种方式总结完毕,如果有其他方式还请留言赐教,谢谢

本文含有隐藏内容,请 开通VIP 后查看

网站公告

今日签到

点亮在社区的每一天
去签到