Generic Top

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE

1. Overview

Spring Boot makes it really easy to work with different database systems, without the hassle of manual dependency management.

More specifically, Spring Data JPA starter provides all the functionality required for seamless integration with several DataSource implementations.

In this tutorial, we’ll learn how to integrate Spring Boot with HSQLDB.

2. The Maven Dependencies

To demonstrate how easy is to integrate Spring Boot with HSQLDB, we’ll create a simple JPA repository layer that performs CRUD operations on customers entities using an in-memory HSQLDB  database.

Here’s the Spring Boot starter that we’ll use for getting our sample repository layer up and running:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
    <version>2.1.1.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.hsqldb</groupId>
    <artifactId>hsqldb</artifactId>
    <version>2.4.0</version>
    <scope>runtime</scope>
</dependency>

Note that we’ve included the HSQLDB dependency as well. Without it, Spring Boot will try to automatically configure a DataSource bean and a JDBC connection pool for us through HikariCP.

As a consequence, if we don’t specify a valid DataSource dependency in our pom.xml file, we’ll get a build failure.

In addition, let’s make sure to check the latest version of spring-boot-starter-data-jpa on Maven Central.

3. Connecting to an HSQLDB Database

For exercising our demo repository layer, we’ll be using an in-memory database. It’s possible, however, to work with file-based databases as well. We’ll explore each of these methods in the sections below.

3.1. Running an External HSQLDB Server

Let’s take a look at how to get an external HSQLDB server running and create a file-based database. Installing HSQLDB and running the server is straightforward, overall.

Here are the steps that we should follow:

  • First, we’ll download HSQLDB and unzip it to a folder
  • Since HSQLDB doesn’t provide a default database out of the box, we’ll create one called “testdb” for example purposes
  • We’ll launch a command prompt and navigate to the HSQLDB data folder
  • Within the data folder, we’ll run the following command:
    java -cp ../lib/hsqldb.jar org.hsqldb.server.Server --database.0 file.testdb --dbname0.testdb
  • The above command will start the HSQLDB server and create our database whose source files will be stored in the data folder
  • We can make sure the database has been actually created by going to the data folder, which should contain a set of files called “testdb.lck”, “testdb.log”, “testdb.properties”, and “testdb.script” (the number of files varies depending on the type of database we’re creating)

Once the database has been set up, we need to create a connection to it.

To do this on Windows, let’s go to the database bin folder and run the runManagerSwing.bat file. This will open HSQLDB Database Manager’s initial screen, where we can enter the connection credentials:

  • Type: HSQL Database Engine
  • URL: jdbc:hsqldb:hsql://localhost/testdb
  • User: “SA” (System Administrator)
  • Password: leave the field empty

On Linux/Unix/Mac, we can use NetBeans, Eclipse, or IntelliJ IDEA to create the database connection through the IDE’s visual tools, using the same credentials.

In any of these tools, it’s straightforward to create a database table either by executing an SQL script in the Database Manager or within the IDE.

Once connected, we can create a customers table:

CREATE TABLE customers (
   id INT  NOT NULL,
   name VARCHAR (45),
   email VARCHAR (45),      
   PRIMARY KEY (ID)
); 

In just a few easy steps, we’ve created a file-based HSQLDB database containing a customers table.

3.2. The application.properties File

If we wish to connect to the previous file-based database from Spring Boot, here are the settings that we should include in the application.properties file:

spring.datasource.driver-class-name=org.hsqldb.jdbc.JDBCDriver 
spring.datasource.url=jdbc:hsqldb:hsql://localhost/testdb 
spring.datasource.username=sa 
spring.datasource.password= 
spring.jpa.hibernate.ddl-auto=update

Alternatively, if we use an in-memory database, we should use these:

spring.datasource.driver-class-name=org.hsqldb.jdbc.JDBCDriver
spring.datasource.url=jdbc:hsqldb:mem:testdb;DB_CLOSE_DELAY=-1
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=create

Please note the DB_CLOSE_DELAY=-1 parameter appended to the end of the database URL. When working with an in-memory database, we need to specify this, so the JPA implementation, which is Hibernate, won’t close the database while the application is running.

4. The Customer Entity

With the database connection settings already set up,  next we need to define our Customer entity:

@Entity
@Table(name = "customers")
public class Customer {
    
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    
    private String name;
    
    private String email;

    // standard constructors / setters / getters / toString
}

5. The Customer Repository

In addition, we need to implement a thin persistence layer, which allows us to have basic CRUD functionality on our Customer JPA entities.

We can easily implement this layer by just extending the CrudRepository interface:

@Repository
public interface CustomerRepository extends CrudRepository<Customer, Long> {}

6. Testing the Customer Repository

Finally, we should make sure that Spring Boot can actually connect to HSQLDB. We can easily accomplish this by just testing the repository layer.

Let’s start testing the repository’s findById() and findAll() methods:

@RunWith(SpringRunner.class)
@SpringBootTest
public class CustomerRepositoryTest {
    
    @Autowired
    private CustomerRepository customerRepository;
    
    @Test
    public void whenFindingCustomerById_thenCorrect() {
        customerRepository.save(new Customer("John", "[email protected]"));
        assertThat(customerRepository.findById(1L)).isInstanceOf(Optional.class);
    }
    
    @Test
    public void whenFindingAllCustomers_thenCorrect() {
        customerRepository.save(new Customer("John", "[email protected]"));
        customerRepository.save(new Customer("Julie", "[email protected]"));
        assertThat(customerRepository.findAll()).isInstanceOf(List.class);
    }
}

Finally, let’s test the save() method:

@Test
public void whenSavingCustomer_thenCorrect() {
    customerRepository.save(new Customer("Bob", "[email protected]"));
    Customer customer = customerRepository.findById(1L).orElseGet(() 
      -> new Customer("john", "[email protected]"));
    assertThat(customer.getName()).isEqualTo("Bob");
}

7. Conclusion

In this article, we learned how to integrate Spring Boot with HSQLDB, and how to use either a file-based or in-memory database in the development of a basic JPA repository layer.

As usual, all the code samples shown in this article are available over on GitHub.

Generic bottom

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE

newest oldest most voted
Notify of
Leos
Guest
Leos

Can you add imports into the test sample? assertThat is not found and when I static import it then I still cannot recolve correct method with parameters

Eric Martin
Member
Eric Martin

These are from AspectJ
https://www.baeldung.com/introduction-to-assertj

Try starting with org.assertj.core.api.Assertions

Alejandro Gervasio
Guest

Thanks for commenting. As Eric Martin posted above, you can use fluent assertions from AssertJ. http://joel-costigliola.github.io/assertj/

In addition, if you’re using Spring Boot’s spring-boot-starter-test: https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-test/2.1.2.RELEASE, you”ll get JUnit, AssertJ, Hamcrest, among other dependencies, without having pull then manually into our pom.xml file.

I hope that helps.