首页 » 文章 » spring boot h2备份和还原--java代码

h2内置的tool可以备份还原h2数据库。

1.首先引入了h2的依赖,注意scope是compile,spring boot 默认是runtime,没法使用

  <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>compile</scope>
        </dependency>

2.要使用文件数据库,内存数据库貌似不行,

spring.datasource.url=jdbc:h2:file:~/db/mydb
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver
spring.jpa.hibernate.ddl-auto=update

3.java 代码

import org.h2.tools.Backup;
import org.h2.tools.Restore;
@RequestMapping("/bak")
    public String bak() throws Exception {
        String file = "~/db/bak/backup-" + JodaDateUtil.formatDate(JodaDateUtil.set000000(new Date()), "yyyy-MM-dd") + ".zip";

        Backup.execute(file, "~/db", "mydb", true);
        return "0k";
    }

    @RequestMapping("/res")
    public String res() throws Exception {
        String file = "~/db/bak/backup-" + JodaDateUtil.formatDate(JodaDateUtil.set000000(new Date()), "yyyy-MM-dd") + ".zip";
        File f = new File(file);
        int i = 1;
        while (!f.exists()) {
            DateTime d = new DateTime();
            d.minusDays(i);
            file = "~/db/bak/backup-" + JodaDateUtil.formatDate(JodaDateUtil.set000000(d.toDate()), "yyyy-MM-dd") + ".zip";
            f = new File(file);
            i++;
        }
        Restore.execute(file, "~/db", "mydb");
        return "0k";
    }

添加新评论