H2数据库,有没有办法重新加载过去的数据?

时间:2016-01-05 00:59:12

标签: spring-boot h2 in-memory

服务器关闭后有没有办法重新加载过去的数据?

我认为我必须将数据保存为文件类型,所以我输入了url添加':file:'我也可以找到一个数据库文件(databasename.mv.db)。但每次重新连接时,文件都被覆盖了。如果有人知道如何处理它,请告诉我。

1 个答案:

答案 0 :(得分:-1)

我喜欢在初始开发阶段/将测试数据加载到应用程序中的方式是将数据存储在CSV文件中,只需在使用ContextRefreshedEvent启动spring-boot应用程序时将其加载到H2中下面:

@Component
public class RootVerbLoader implements ApplicationListener<ContextRefreshedEvent> {

private static final int SOURCE_LANGUAGE = 1;
private static final int TARGET_LANGUAGE = 2;
private RootVerbRepository repo;

@Autowired
public void setRepo(RootVerbRepository repo) {
    this.repo = repo;
}

@Override
public void onApplicationEvent(ContextRefreshedEvent arg0) {

    loadDataFromCSV("classpath:hanasu.csv", "to speak", "はなす");
    loadDataFromCSV("classpath:iku.csv", "to go", "いく");
    loadDataFromCSV("classpath:iu.csv", "to say", "いう");
    loadDataFromCSV("classpath:kaku.csv", "to write", "かく");
    loadDataFromCSV("classpath:kasegu.csv", "to earn", "かせぐ");
    loadDataFromCSV("classpath:kuru.csv", "to come", "くる");
    loadDataFromCSV("classpath:matsu.csv", "to wait", "まつ");
    loadDataFromCSV("classpath:miru.csv", "to look", "みる");
    loadDataFromCSV("classpath:naru.csv", "to become", "なる");
    loadDataFromCSV("classpath:nomu.csv", "to drink", "のむ");
    loadDataFromCSV("classpath:shinu.csv", "to die", "しぬ");
    loadDataFromCSV("classpath:suru.csv", "to do", "する");
    loadDataFromCSV("classpath:yobu.csv", "to call", "よぶ");
}

private void loadDataFromCSV(String filename, String source, String target) {

    Set<TranslationPair> conjugations = new HashSet<>();

    try {

        ResultSet rs = new Csv().read(filename, null, null);
        int i = 1;
        while (rs.next()) {
            conjugations.add(
                new TranslationPair(
                    rs.getString(SOURCE_LANGUAGE),
                    rs.getString(TARGET_LANGUAGE),
                    i
                )
            );
            i++;
        }

        rs.close();

    } catch(SQLException se) {
        se.printStackTrace();
    }

    repo.save(new RootVerb(source, target, conjugations));
}

}

将数据写出到CSV文件的代码也非常简单:

SimpleResultSet rs = new SimpleResultSet();
rs.addColumn("NAME", Types.VARCHAR, 255, 0);
rs.addColumn("EMAIL", Types.VARCHAR, 255, 0);
rs.addRow("Bob Meier", "bob.meier@abcde.abc");
rs.addRow("John Jones", "john.jones@abcde.abc");
new Csv().write("data/test.csv", rs, null);

我发现这提供了一种非常快速的方法来原型化数据结构/表模式,而无需编写任何sql脚本或完全做很多工作。开始真的很快。