How to create and get started with Embedded Apache Derby database in Dropwizard project (Angular 7 front-end)

六眼飞鱼酱① 提交于 2019-12-06 04:25:07

Consider the embedded database like a full-fledged database, that instead of being in a different environment, and maybe requiring a network connection, is packed along with your application and run in the same JVM. The same mechanisms applies between the two.

The embedded Derby Driver is located inside the derby.jar file, so it is required to have it in the classpath of your application. It should be located under %DERBY_INSTALL%\lib\, where %DERBY_INSTALL% is the installation directory. You can see by the image where it is contained.

From Oracle

Any JDBC 4.0 drivers that are found in your class path are automatically loaded. (However, you must manually load any drivers prior to JDBC 4.0 with the method Class.forName.)

What that means is that if the Derby driver is a JDBC 4.0 driver, you don't have to do anything else besided getting a connection via DriverManager.
If it is not a JDBC 4.0 driver, you'll have to instantiate the Driver with

Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();

Appartently you'll need that piece of code above.
Now simply get a hold on a Connection object.

DriverManager.getConnection("jdbc:derby:dbName;create=true");

From there on, you can create Statement(s) as you like. Which means you can create tables, insert rows, update rows, delete rows, etc.

To gracefully shutdown the embedded Derby database, you need to use

DriverManager.getConnection("jdbc:derby:dbName;shutdown=true"); // see the same database name "dbName"

prior to quitting the main application. It is not mandatory, but recommended.


You can create a utility class to hold an EmbeddedDataSource (docs), which will provide connections around your application.

public final class EmbeddedDerby {
   private static final DataSource DATA_SOURCE;

   static {
      // Initialize DATA_SOURCE with EmbeddedDataSource
   }

   ...

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