SpringBoot 自动建表

本文介绍了如何在Spring Boot应用中使用@EnableScheduling注解启用定时任务,并通过ScheduledConfigurer实现每月自动创建数据表,确保数据同步。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.在启动类中添加 @EnableScheduling 注解

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
@MapperScan("com.gactoyota.system.mapper")
@EnableScheduling
public class SystemApplication {

    public static void main(String[] args) {
        SpringApplication.run(SystemApplication.class, args);
    }

}

2 编写config 实现 SchedulingConfigurer

/**
 * 自动分表配置
 * @Author LB
 * @Date 2022/4/2
 */
@Component
@Slf4j
public class ScheduledConfig implements SchedulingConfigurer {


    @Value("${spring.datasource.driver-class-name}")
    private String driverName;

    @Value("${spring.datasource.url}")
    private String url;

    @Value("${spring.datasource.username}")
    private String username;

    @Value("${spring.datasource.password}")
    private String password;

    @Resource
    private IDeviceDataTabsService deviceDataTabsService;


    @SneakyThrows
    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        // 查询这个当前月份的表是否已经创建
        // 获取当前月份
        Date date = new Date();
        String dataForStr = dateFormat.format(date);
        String[] split = dataForStr.split("-");
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < split.length; i++) {
            if (i <= 1) {
                stringBuilder.append(split[i]);
            }
        }
        stringBuilder.append("01");
        String thisSysDate = stringBuilder.toString();
        QueryWrapper<DeviceDataTabs> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("table_name", thisSysDate);
        //  本月表未创建则自动创建并保存
        List<DeviceDataTabs> list = deviceDataTabsService.list(queryWrapper);
        if (list.size() == 0) {
            // 建表
            String tableName = autoTable(thisSysDate);
            log.info("表创建成功!");
            // 新增数据库数据
            DeviceDataTabs deviceDataTabs = new DeviceDataTabs();
            deviceDataTabs.setCreateDate(date);
            deviceDataTabs.setTableName(tableName);
            if (deviceDataTabsService.save(deviceDataTabs)) {
                log.info("当前月份表初始化成功!!【" + tableName + "】");
            }
        }


        // 已经创建则进入定时任务
        scheduledTaskRegistrar.addTriggerTask(
                // 添加任务内容(Runnable)
                () -> {

                    // 获取当前时间
                    Date dateOne = new Date();
                    String thisDate = dateFormat.format(dateOne);

                    String thisDateDay = thisDate.replace("-", "");
                    // 调用创建表格时间
                    try {
                        thisDateDay = autoTable(thisDateDay);
                        log.info("表创建成功!");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    log.info("thisDateDay : " + thisDateDay);
                    DeviceDataTabs deviceDataTabs = new DeviceDataTabs();
                    deviceDataTabs.setCreateDate(date);
                    deviceDataTabs.setTableName(thisDateDay);
                    deviceDataTabsService.save(deviceDataTabs);
                }

                // 设置执行周期(Trigger)
                , triggerContext -> {
                    // 每月1号 凌晨0点调用定时任务
                    String cron = "0 0 0 1 * ?";
                    log.info("定时创建表任务启动!");
                    //返回执行周期(Date)
                    return new CronTrigger(cron).nextExecutionTime(triggerContext);
                }
        );
    }

    /**
     * 创建数据表
     * @param tabName 表名
     * @throws Exception
     */
    public String autoTable(String tabName) throws Exception {
        Class.forName(driverName);
        Connection conn = DriverManager.getConnection(url, username, password);
        Statement stat = conn.createStatement();
        String tableName = "device_data_" + tabName;
        //创建表
        stat.executeUpdate("CREATE TABLE " + tableName + " (" +
                "  `id` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '主键Id'," +
                "  `numerial_number` decimal(6, 3) NULL DEFAULT NULL COMMENT '数值'," +
                "  `picture_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '图片名称'," +
                "  `create_date` datetime(0) NULL DEFAULT NULL COMMENT '创建时间'," +
                "  `voltage` decimal(3, 1) NULL DEFAULT NULL COMMENT '电压'," +
                "  `device_id` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '设备Id'," +
                "  `data_status` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '数据状态'," +
                "  `is_deleted` int NULL DEFAULT 0 COMMENT '是否已删除'," +
                "  PRIMARY KEY (`id`) USING BTREE" +
                ") ");

        //查询数据
        ResultSet result = stat.executeQuery("select * from " + tableName);
        while (result.next()) {
            System.out.println(result.getInt("id") + " " + result.getString("name"));
        }

        //关闭数据库
        result.close();
        stat.close();
        conn.close();
        return tableName;
    }

}
### 如何在Spring Boot中配置Quartz以实现自动 在Spring Boot项目中集成Quartz并启用其自动数据库的功能,可以通过调整`application.properties`或`application.yml`中的属性来完成。以下是详细的说明: #### 配置Quartz数据源 为了使Quartz能够连接到数据库并自动生成所需的结构,需要定义一个专用的数据源。这通常通过设置`spring.datasource.*`属性以及指定Quartz的相关参数来实现。 ```properties # 数据库连接信息 spring.datasource.url=jdbc:mysql://localhost:3306/quartz_db?useSSL=false&serverTimezone=UTC spring.datasource.username=root spring.datasource.password=password spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver # Quartz 自动配置 spring.quartz.job-store-type=jdbc spring.quartz.properties.org.quartz.jobStore.useProperties=true spring.quartz.properties.org.quartz.jobStore.dataSource=myDataSource spring.quartz.properties.org.quartz.jobStore.tablePrefix=QRTZ_ spring.quartz.properties.org.quartz.jobStore.isClustered=true spring.quartz.properties.org.quartz.dataSource.myDataSource.jndiURL=java:/comp/env/jdbc/MyDS ``` 上述配置中指定了Quartz使用的数据源名称为`myDataSource`,并且设置了前缀为`QRTZ_`的名模式[^1]。 #### 设置驱动程序代理类 根据Quartz官方文档议,在SQL脚本中有提到关于MySQL的最佳实践,推荐使用特定版本的JDBC驱动程序,并确保启用了InnoDB存储引擎以减少锁定问题的发生概率。此外还需要正确设定`driverDelegateClass`属性值为标准JDBC委托类实例化路径。 ```properties spring.quartz.properties.org.quartz.jobStore.driverDelegateClass=org.quartz.impl.jdbcjobstore.StdJDBCDelegate ``` 此行代码明确了Quartz应采用的标准JDBC委派机制[^2]。 #### 使用Spring Boot Starter简化过程 如果希望进一步降低复杂度,则可以考虑引入`sprint-boot-starter-quartz`模块。它会预先封装好大部分基础功能组件,从而省去了手动编写某些核心类的工作量。不过对于更高级别的定制需求来说,可能仍需查阅额外资料或者参考其他博文深入探讨具体实现细节[^4]。 最后提醒一下开发者们注意检查所选数据库是否支持事务特性及其兼容性状况;另外也要记得定期备份重要业务逻辑以防意外丢失! ```python import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class QuartzAutoConfigApplication { public static void main(String[] args) { SpringApplication.run(QuartzAutoConfigApplication.class, args); } } ``` 以上展示了基本的应用入口文件样例。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值