Spring H2嵌入式数据库文件?

时间:2012-11-01 15:55:52

标签: database spring h2

我目前使用嵌入式码头和H2数据库在maven上运行我的petproject:

<jdbc:embedded-database id="dataSource" type="H2">
   <jdbc:script location="/WEB-INF/database.sql"/>
</jdbc:embedded-database>

每次运行服务器时,此设置都会重置我的数据库。我想将数据库保存为磁盘中的文件,这样我就不会在每次服务器启动时丢失数据。我该如何做到这一点?

2 个答案:

答案 0 :(得分:9)

您可以通过连接字符串来控制它。

jdbc:h2:~/test; # saves to the file ~/test
jdbc:h2:mem:db1 # in memory

更多信息here

编辑:

在Spring H2配置中,似乎连接字符串是hard-coded,所以我认为这意味着你必须通过扩展EmbeddedDatabaseConfigurer来编写自己的实现,假设没有其他方法可以更改在H2EmbeddedDatabaseConfigurer

中设置后的连接字符串

答案 1 :(得分:3)

老问题,但我花了很多时间搞清楚如何将嵌入式H2数据库保存到文件中,我想分享我学到的东西。

正如@ebaxt所说,您可以在连接字符串中配置嵌入式数据库的位置。 如果要将其保存在文件系统中,请使用~/语法:

jdbc:h2:~/example/embeddedDb

如果要将其保存在项目文件夹中,则必须使用./语法

jdbc:h2:./example/embeddedDb

这将在您的主文件夹内的embeddedDb.mv.db文件夹中或项目根文件夹中创建example文件。 但是每次应用程序启动时都会擦除数据库。为了避免这种情况,我使用INIT属性告诉H2只有在它不存在时才创建模式(在我的情况下为Queue):

INIT=create schema if not exists Queue;

然后在您的DDL脚本中,您必须使用create table if not exists语句来创建所有表:

// create-db.sql
    CREATE TABLE IF NOT EXISTS Queue (
       id INTEGER PRIMARY KEY AUTO_INCREMENT,
       ...
   );

告诉H2每次获取连接时都运行脚本:

// if you want to store the script in the file system
runscript from '~/example/create-db.sql'

// if you want to store the script in the project folder
runscript from './example/create-db.sql'

总结这是以java注释方式创建数据库(EmbeddedDb)所要做的:

    import org.springframework.jdbc.datasource.DriverManagerDataSource;

    @Bean
    DataSource datasource(){

        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("org.h2.Driver");
        dataSource.setUsername("embedded");
        dataSource.setPassword("embedded");
        dataSource.setUrl("jdbc:h2:~/example/EmbeddedDb;INIT=create schema if not exists Queue\\; runscript from '~/example/create-db.sql'");

        return dataSource;
    }

或使用XML:

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"
        destroy-method="close">
        <property name="driverClassName" value="org.h2.Driver" />
        <property name="url" value="jdbc:h2:~/example/EmbeddedDb;INIT=create schema if not exists Queue\; runscript from '~/example/create-db.sql'" />
        <property name="username" value="embedded" />
        <property name="password" value="embedded" />
    </bean>

使用此方法,只有在应用程序第一次运行或数据库文件不存在时才会创建数据库。否则只会加载连接。

您还可以使用hsqldb库通过一个漂亮的界面监控数据库状态,添加以下bean:

    import org.h2.tools.Server;
    import org.hsqldb.util.DatabaseManagerSwing;

    @Bean(initMethod = "start", destroyMethod = "stop")
    public Server startDBManager() throws SQLException {
        DatabaseManagerSwing.main(new String[] { "--url", "jdbc:h2:~/example/EmbeddedDb", "--user", "embedded", "--password", "embedded" });
        return Server.createWebServer();
    }

参考文献:

http://www.mkyong.com/spring/spring-embedded-database-examples/

http://www.h2database.com/html/features.html#embedded_databases(在Connect部分执行SQL)

相关问题