Does Spring embedded database support different SQL dialects?

倾然丶 夕夏残阳落幕 提交于 2019-12-18 02:42:06

问题


H2 has a range of compatibility modes for various other databases such as MS SQL Server, MySQL, Oracle, etc that support different SQL dialects. However, when setting up an embedded database in Spring I do not find any corresponding setting. Does this imply that I have to use "plain" SQL without any dialect specific features if I for example use Oracle in production and H2 during test? Have I overlooked something?


回答1:


According to the H2 doc, the Oracle compatibility mode is quite limited.

For instance, you can not use PL/SQL procedures.

If you use Spring's EmbeddedDatabase, you cannot set the compatibility mode as-is; you have to implement you own EmbeddedDatabaseConfigurer and specify the compatibility mode through the JDBC URL (see below).

But also, to use the compatibility mode with H2 and Spring, you just have to set the mode in your JDBC URL (so it is not Spring related) in a classic way, using a DataSource:

jdbc:h2:~/test;MODE=Oracle

And if you use Hibernate, you have to specify the Oracle dialect instead of the H2 one.




回答2:


which version of H2 database? per the documentation, you can set compatible mode by SQL statement (http://www.h2database.com/html/features.html#compatibility)

SET MODE PostgreSQL

just add this statement into your first sql script file loaded by Spring jdbc embedded-database




回答3:


You have 2 options:

  1. use spring to start the H2 database as follows (check setName() to see how to pass H2 specific URL parameters to spring builder):

Spring code generates the URL as follows:

String.format("jdbc:h2:mem:%s;DB_CLOSE_DELAY=-1", databaseName)

So, in setName() you can all any H2 specific parameter in the URL.

private DataSource dataSource() {
    EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
    EmbeddedDatabase db = builder
        .setType(EmbeddedDatabaseType.H2)
        .setName("testdb;DATABASE_TO_UPPER=false;MODE=Oracle")
        .addScript("schema.sql")
        .addScript("data.sql")
        .build();
    return db;
}
  1. configure directly the DB URL, sth like:

    org.h2.jdbcx.JdbcDataSource dataSource = new org.h2.jdbcx.JdbcDataSource(); dataSource.setURL("jdbc:h2:testdb;MODE=MySQL;DATABASE_TO_UPPER=false;INIT=runscript from 'src/test/resources/schema.sql'\;runscript from 'src/test/resources/data.sql'");

The main different is that (2) is executing scripts defined at INIT for every database connection creation and not once per DB creation! This causes various issues, like INSERTs failing due to duplicate keys etc..



来源:https://stackoverflow.com/questions/9171743/does-spring-embedded-database-support-different-sql-dialects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!