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

Pwi
  • 101
  • 1
  • 1
  • 6
  • Did you test first application? – nurgasemetey Oct 01 '16 at 16:54
  • Yes I did and works fine. I can get records without problems. – Pwi Oct 01 '16 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. – harshavmb Oct 01 '16 at 19:06
  • Java isn't using any .dll file. Read-only mode is nothing to do with a database connection conceptually. – Pwi Oct 01 '16 at 19:12

1 Answers1

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

Beck Yang
  • 3,004
  • 2
  • 21
  • 26
  • Can you tell me where to but this XML code? How can I opean the this bean XML? – Pwi Oct 05 '16 at 19:42
  • For spring boot app, you can add XML configuration using `@ImportResource(value="classpath:/package/filename.xml")`. [Here is a example](http://javarticles.com/2016/02/spring-importresource-annotation-example.html) – Beck Yang Oct 06 '16 at 14:21