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?
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
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.
You have 2 options:
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;
}
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..
Related
My application was using Mongo DB earlier. Now, I'm shifting to PostgreSQL. For that, I've been migrating queries and all. But, I was being blocked by issue. In MongoDB connection, we've some MongoClientOptions used to improve the performance of the application. In some way, I want to set these options with JDBC for PostgreSQL also.
I've tried and searched the same functions in JDBC DriverManager class. But didn't find any.
MongoDB connection options used are added below,
How can I set these options for JDBC client for PostgreSQL?
MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
builder.threadsAllowedToBlockForConnectionMultiplier(1000);
builder.maxConnectionIdleTime(60* 1000 * 5);
builder.connectionsPerHost(100000);
MongoClientOptions options = builder.build();
mongoClient = new MongoClient(hostname, options);
In JDBC you pass a Properties object with some JDBC-standard properties ("user" and "password") and driver-specific properties, or pass the properties as part of the JDBC-url (with driver-specific properties and driver-specific syntax), or you configure things using a DataSource and its getters and setters.
For PostgreSQL JDBC refer to the section Connecting to the Database
For almost any serious usage of JDBC, you should not use DriverManager directly as it will create a new physical connection for each request. Instead use a javax.sql.DataSource implementation that provides connection pooling, either provided by your driver (those usually aren't very good though), a third-party library like HikariCP, or one built into your JavaEE application server.
So i have a spring based application which talks to an oracle 12c database and i want to turn off case sensitivity for the jdbctemplate.
I know this can be done by executing the following statements before i call the actual query. But i dont want to call these statements each and every time i make a database query. Is there something i can configure before my application starts?
ALTER SESSION SET NLS_COMP=LINGUISTIC;
ALTER SESSION SET NLS_SORT=BINARY_CI;
The JdbcTemplate itself does not provide any sort of init scripts. But some DataSource implementations might provide said feature.
For example the Tomcat JDBC DataSource has a setInitSQL(String sql)-method. The given query is run when a connection is first created.
Spring Boot provides a common application.properties config option for configuring the tomcat jdbc datasource:
spring.datasource.tomcat.initSQL=ALTER SESSION SET...
I'm using Spring Boot and JDBC for my database connection. I placed schema.sql at the classpath to initialize a schema and tables.
Because the schema doesn't exist yet while connecting to the datasource, I have to configure the datasource in application.properties like so:
spring.datasource.url=jdbc:mysql://localhost:3306/
schema.sql:
CREATE DATABASE IF NOT EXISTS <schema_name>
USE <schema.name>;
CREATE TABLE...
So I select the schema after creating it. This obviously doesn't persist for too long.
How do I configure this properly? Is there a way to select a default schema after the create script or maybe change the datasource url?
With JDBC you need to use Connection.setCatalog to switch between databases. You should not use USE <databasename> as the JDBC driver itself needs to be aware of which database it is operating on.
Based on your code from the schema.sql
USE <schema.name>;
This will not work for your java environment. The schema.sql will be executed and finished, which will not cater your requirement to set the default schema.
The General approach will be to use JDBC URL as;
jdbc:mysql://localhost:3306/DB_NAME
This will set the default db as DB_NAME.
Assumptions: I am assuming that you want to connect to single node DB without any loadbalancer or failover mechanism to be used. URL may change based on these features to be configured.
If you are not specifying the DB_NAME in the URL, it means their is no default schema.
You have 2 options to access the DB in that case.
1) Always use the Connection.setCatalog() method to specify the desired database in JDBC applications, rather than the USE database statement.
2) fully specify table names using the database name (that is, SELECT dbname.tablename.colname FROM dbname.tablename...) in your SQL. Opening a connection without specifying the database to use is generally only useful when building tools that work with multiple databases, such as GUI database managers.
For more details refer to the below mysql portal for reference.
https://dev.mysql.com/doc/connector-j/en/connector-j-reference-configuration-properties.html
I used to run my Java code with Hibernate to mysql.
Some logical changes led me to decide that I don't need to save the data in the database, but in java class that will handle it as a database (The data is delete in every startup of the application).
How can I do in Hibernate? is there a way to create an in memory database?
Consider H2 (recommended) or HSQLDB. You can certainly use Hibernate with them. In fact, HSQLDB was the database used by default in Hibernate for their test suite (I think they just changed to H2).
Take a look at Apache Derby.
You could also use SqlLite, which is an in-memory database. I'm just about to start using it with NHibernate for the same purpose in unit tests.
You just need to:
add the driver for the database you want to use and change the hibernate settings for this driver,
change the setting hibernate database dialect,
change the jdbc connection String
(add the jars for the database)
For example for Hypersonic H2 Database:
driverClassName = org.h2.Driver
dialect = org.hibernate.dialect.H2Dialect
connection string = jdbc:h2:mem:test
I want to use an in-memory database to test my application, but it needs to support XA distributed transactions. My first idea for an in-memory database was HSQLDB, but it appears not to support XA. Are there any?
Looks like H2 supports this.
Both H2 database and HSQLDB support it, couldn't find any other java embedded databases even in 2019. But it's not correctly implemented in either of them: the transaction is rolled back as soon as the client disconnects. According to the X/Open spec, when a database prepares a transaction, its data should be persistently stored and must be available to be committed later.
In H2 the XA code is unmaintained.
If you want an XA-supporting database for your tests, you can use Postgres using the TestContainers project:
#ClassRule
public static PostgreSQLContainer container = new PostgreSQLContainer<>("postgres:12.1")
.withCommand("postgres -c max_prepared_transactions=10");
Then create a datasource like this:
PGXADataSource dataSource = new PGXADataSource();
dataSource.setURL(container.getJdbcUrl());
dataSource.setUser(container.getUsername());
dataSource.setPassword(container.getPassword());
dataSource.setDatabaseName(container.getDatabaseName());