Multiple independent H2 databases within one JVM

吃可爱长大的小学妹 提交于 2019-12-04 19:34:31

Yes it is possible to do so. Each database will contain its own mini environment, no possible pollution between databases.

You could for example use a jdbc url based on the user id or login from the user:

  • jdbc:h2:user1 in H2 1.3.x embedded mode
  • jdbc:h2:./user1 in H2 1.4.x embedded mode
  • jdbc:h2:tcp://localhost/user1 in tcp mode

You can use any naming convention for the database name, provided your OS allows it: user1, user2, etc... or truly the name of the login.

Tips:

  • use the server mode rather than the embedded mode, allowing for same user multiple connections from multiple sessions/hosts
  • have a schema migrator (like flyway) to initialize each newly created db
  • ensure you manage name collisions at the top level of your app, and possibly store these databases and corresponding logins in a dedicated database as well

Caveats:

  • do not use a connection pool as connections will be difficult to reuse
  • You must make sure IFEXISTS=TRUE is not used on the server
  • avoid using tweaks on the jdbc url, like turning LOG=0, UNDO_LOG=0, etc...
  • I do not know if you'll have a limitation from your OS or the JVM on how many db files could be opened like this.
  • I do not know if such setting can be tweaked from the manual pages. I could not find one.

Please refer to H2 manual in doubts of url parameters.

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