Setting up an embedded Derby database in a standalone Java application

Clark Minor picture Clark Minor · Dec 9, 2010 · Viewed 57.3k times · Source

I'm trying to setup an embedded Derby database for a standalone Java application, but after pouring through all sorts of documentation, I just can't seem to find any simple explanations or examples. I'm using Eclipse with the Derby plugin and have enabled Derby nature for my project.

I found an example of using an embedded Derby database in a standalone address book as well as an overview of using Derby in Eclipse (that doesn't seem to cover the embedded deployment), but I still feel like I'm missing something fundamental.

This is my first time attempting to use a database with Java, and I'm a little confused, so here are my basic questions:

  • What's the basic philosophy (or model) for how Java interacts with a Derby database (in an embedded deployment)? Are their important design patterns to be followed?
  • Do I need to create some type of database constructor (that includes table structure, etc.) in a class, or is that all done with some other tool?
  • One the database is created and saved, how do I "start" it up? And where is the actual database saved?

Snippets of code would be very helpful!

Answer

Jan Bodnar picture Jan Bodnar · Mar 22, 2017

To use Derby in Java in embedded mode, we need to do the following steps:

  • Use the org.apache.derby.jdbc.EmbeddedDriver driver, located in the derbyclient Maven dependency
  • Use the connection string for embedded mode: jdbc:derby:dbname
  • Set up the Derby system home: System.setProperty("derby.system.home", "/home/janbodnar/.derby");
  • Shut down Derby programatically at the end: DriverManager.getConnection("jdbc:derby:;shutdown=true");
  • Handle XJ015 error, which is triggered at successfull shutdown

Full working examples can be found at my Java JDBC Derby programming tutorial.