2

I created a H2 In-Memory Database in Spring framework like this:

  EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
  EmbeddedDatabase db = builder
            .setType(EmbeddedDatabaseType.H2) //.H2 or .DERBY
            .addScript("create-table.sql")
            .build();

I would like to make another Java application which connect to this Database and access the data from that.

I can connect to the database with this code:

Connection connecton = DriverManager.getConnection("jdbc:h2:mem:testdb","sa","");

But this returns me an empty database, without tables and records.

Here is a description which tell how to solve this problem.

Unfortunately I cannot understand how to do work with Spring container and the MethodInvokingBean, because I don't know where to code, how to use, how it works etc.

I would appreciate that someone make a short tutorial.

Thanks

4
  • Did you test first application? Commented Oct 1, 2016 at 16:54
  • Yes I did and works fine. I can get records without problems. Commented Oct 1, 2016 at 17:41
  • Does the second application run DDL scripts similar to first application? I meant creating/altering tables. If so, it would wipe out the data persisted by first application. If you are using second application just for reading data, you can use read-only mode. Commented Oct 1, 2016 at 19:06
  • Java isn't using any .dll file. Read-only mode is nothing to do with a database connection conceptually. Commented Oct 1, 2016 at 19:12

1 Answer 1

1

You can start a TCP server to share the database. Adding following configuration:

<bean id="h2Server" class="org.h2.tools.Server" factory-method="createTcpServer" init-method="start" destroy-method="stop">
  <constructor-arg value="-tcp,-tcpAllowOthers,-tcpPort,9092"/>
</bean>

Once the server start up, other Java application can connect to it using jdbc:h2:tcp://localhost:9092/mem:testdb

Sign up to request clarification or add additional context in comments.

2 Comments

Can you tell me where to but this XML code? How can I opean the this bean XML?
For spring boot app, you can add XML configuration using @ImportResource(value="classpath:/package/filename.xml"). Here is a example

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.