#1
This guide shows how to use Apache Derby in-memory mode for fast and isolated testing of Spring Boot applications.

1. Add Dependencies

In pom.xml:
<dependency>
  <groupId>org.apache.derby</groupId>
  <artifactId>derby</artifactId>
  <scope>test</scope>
</dependency>

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-test</artifactId>
  <scope>test</scope>
</dependency>

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

2. Configure Derby for Tests

Create src/test/resources/application.properties:
spring.datasource.url=jdbc:derby:memory:testDB;create=true
spring.datasource.driver-class-name=org.apache.derby.jdbc.EmbeddedDriver
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.show-sql=true
This ensures Derby runs only during tests and resets after each run.

3. Create Sample Entity

import jakarta.persistence.*;

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;

    // getters and setters
}

4. Repository

import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User, Long> {
}

5. Write JUnit Test

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;

import static org.assertj.core.api.Assertions.assertThat;

@DataJpaTest
class UserRepositoryTest {
    @Autowired
    private UserRepository repo;

    @Test
    void testSaveAndFind() {
        User user = new User();
        user.setName("Alice");
        repo.save(user);

        var users = repo.findAll();
        assertThat(users).hasSize(1);
        assertThat(users.get(0).getName()).isEqualTo("Alice");
    }
}

6. Run Tests

Run with Maven:
mvn test
Derby runs in-memory, creates schema, and drops it automatically after tests.

image quote pre code