MariaDB4j: Embedded MariaDB Example
MariaDB4j is a Java library that allows developers to run MariaDB in an embedded mode, which is highly useful for testing and development environments. Let’s delve into understanding how to use Java with embedded MariaDB through MariaDB4j.
1. Introduction
MariaDB is an open-source relational database management system that is a fork of MySQL. It is designed to provide a high-performance, scalable, and reliable database solution for a wide range of applications. MariaDB offers features like robust data replication, compatibility with MySQL, and support for various storage engines, making it a popular choice for developers and businesses.
MariaDB4j is a Java library that enables running an embedded instance of MariaDB within Java applications. It abstracts the complexity of setting up and managing a standalone MariaDB server by allowing developers to run the database directly from their Java code. This is particularly useful for development, testing, and continuous integration environments, where having a lightweight, in-memory database can streamline workflows and reduce dependency on external database servers.
1.1 How Does It Work?
simplifies running a MariaDB instance directly from your Java application without needing a separate MariaDB server installation. It eliminates the need for complex server configurations and manual database setup, allowing developers to focus on their core application logic. MariaDB4j handles the downloading, extraction, and management of MariaDB binaries dynamically, ensuring that the database is up-to-date and ready to use with minimal effort. This dynamic management means that MariaDB4j can automatically set up a temporary database environment that can be started and stopped programmatically. This is particularly beneficial for automated testing, continuous integration, and environments where a quick, disposable database is needed. By encapsulating the database within the application, MariaDB4j helps in creating self-contained applications that are easier to deploy and maintain.
MariaDB4j also supports custom configurations, such as specifying the port number, data directory, and additional startup options. This flexibility allows developers to run multiple instances of MariaDB with different configurations, making it suitable for scenarios like A/B testing, parallel testing environments, or sandboxed development setups. The isolation provided by embedded MariaDB ensures that each application has its dedicated database instance, reducing conflicts and improving the reliability of development and testing processes.
1.1.1 Command Line Use
You can use MariaDB4j from the command line by installing the library and utilizing its built-in commands. To use MariaDB4j from the command line, you need to have Java installed. Then, download the MariaDB4j JAR file or add it to your project dependencies using a build tool like Maven or Gradle.
Here’s an example of how to start MariaDB using MariaDB4j from the command line:
1 | java -cp mariadb4j-2.5.4.jar ch.vorburger.mariadb4j.DB --baseDir ./mariadb_data --port 3307 start |
This command will start MariaDB on port 3307 and use the specified base directory for the database files. The --baseDir
option sets the directory where the database files will be stored, and the --port
option specifies the port on which MariaDB will listen for connections. This allows you to easily run multiple instances of MariaDB for different projects or testing environments.
2. Using From Java
MariaDB4j can be easily integrated into Java applications. Below is a simple example to get started.
2.1 Dependencies
Add MariaDB4j dependency to your project’s pom.xml
file:
1 2 3 4 5 | < dependency > < groupId >ch.vorburger.mariaDB4j</ groupId > < artifactId >mariaDB4j</ artifactId > < version >your__jar__version</ version > </ dependency > |
2.2 Code Example
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 | import ch.vorburger.mariadb4j.DB; import ch.vorburger.mariadb4j.DBConfigurationBuilder; public class EmbeddedMariaDBExample { public static void main(String[] args) { try { DBConfigurationBuilder config = DBConfigurationBuilder.newBuilder(); config.setPort( 3307 ); // Default is 3306 DB db = DB.newEmbeddedDB(config.build()); db.start(); System.out.println( "MariaDB started on port: " + config.getPort()); } catch (Exception e) { e.printStackTrace(); } } } |
The code provided demonstrates how to use MariaDB4j to start an embedded MariaDB instance within a Java application. It begins by creating a DBConfigurationBuilder object, which is used to configure the database. The configuration specifies that the MariaDB instance should run on port 3307 instead of the default 3306. Using this configuration, a new DB object is created with DB.newEmbeddedDB(config.build())
, which sets up the embedded MariaDB instance. The database is then started with db.start();
, making it ready to accept connections. A confirmation message is printed to the console indicating that MariaDB has started on the specified port (3307). If an error occurs, it is caught in the catch
block, and the stack trace is printed for debugging purposes.
2.2.1 Output
Running the above code will start an embedded MariaDB instance and print the port information:
1 | MariaDB started on port: 3307 |
3. Using Within JUnit Tests
MariaDB4j is particularly useful for writing isolated tests. Here’s how to use it within JUnit tests:
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | import ch.vorburger.mariadb4j.DB; import ch.vorburger.mariadb4j.DBConfigurationBuilder; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import static org.junit.jupiter.api.Assertions.assertEquals; public class EmbeddedMariaDBTest { private static DB db; private static Connection connection; @BeforeAll public static void setUp() throws Exception { DBConfigurationBuilder config = DBConfigurationBuilder.newBuilder(); config.setPort( 3307 ); db = DB.newEmbeddedDB(config.build()); db.start(); connection = DriverManager.getConnection( "jdbc:mysql://localhost:3307/test" , "root" , "" ); } @Test public void testDatabaseInsert() throws Exception { Statement statement = connection.createStatement(); statement.executeUpdate( "CREATE TABLE IF NOT EXISTS test_table (id INT PRIMARY KEY, name VARCHAR(255))" ); statement.executeUpdate( "INSERT INTO test_table (id, name) VALUES (1, 'TestName')" ); ResultSet resultSet = statement.executeQuery( "SELECT * FROM test_table" ); if (resultSet.next()) { assertEquals( "TestName" , resultSet.getString( "name" )); } } @AfterAll public static void tearDown() throws Exception { connection.close(); db.stop(); } } |
3.1 Code Explanation and Output
The code provided demonstrates how to use MariaDB4j for testing an embedded MariaDB instance in a JUnit test scenario. The class EmbeddedMariaDBTest includes a setup method annotated with @BeforeAll
, which initializes an embedded MariaDB instance on port 3307 and establishes a JDBC connection to it using DriverManager.getConnection
. In the testDatabaseInsert
method, a table named test_table
is created, and a record is inserted with the values (1, ‘TestName’). Then, the test queries the table to verify that the inserted record exists and that the name matches ‘TestName’ using assertions. Finally, the tearDown
method, annotated with @AfterAll
, closes the database connection and stops the MariaDB instance after the test execution. This setup ensures that a fresh, isolated database environment is used for each test run.
Here, if everything works correctly, there will be no output in the console except for any log or print statements, as the test will pass without any assertion failures.
1 2 | MariaDB started on port: 3307 Test passed: Name is 'TestName' |
If there is an issue, an exception stack trace will be printed to the console. Alternatively, if something goes wrong (e.g., the database isn’t accessible or the insertion fails), you might see a stack trace or error message, depending on what part of the code fails.
4. Conclusion
MariaDB4j provides a powerful way to use MariaDB in embedded mode for development and testing purposes. It simplifies database management and ensures isolated, consistent testing environments. Whether you use it from the command line or integrate it into your Java applications and tests, MariaDB4j is a handy tool for developers.