This guide shows how to integrate
Apache Derby with
Spring Data JPA to manage data easily using repositories and minimal boilerplate code.
1. Add Dependencies
In
pom.xml
:
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derby</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
2. Configure Derby
In
application.properties
:
spring.datasource.url=jdbc:derby:memory:demoDB;create=true
spring.datasource.driver-class-name=org.apache.derby.jdbc.EmbeddedDriver
spring.jpa.hibernate.ddl-auto=update
This sets up an in-memory Derby database that initializes on startup.
3. Create Entity
import jakarta.persistence.*;
@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String role;
// getters and setters
}
4. Create Repository
import org.springframework.data.jpa.repository.JpaRepository;
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
}
Spring Data JPA automatically provides CRUD methods like
save
,
findAll
,
findById
, and
deleteById
.
5. Service Layer (Optional)
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class EmployeeService {
private final EmployeeRepository repo;
public EmployeeService(EmployeeRepository repo) {
this.repo = repo;
}
public List<Employee> getAll() {
return repo.findAll();
}
public Employee save(Employee e) {
return repo.save(e);
}
}
6. REST Controller
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/employees")
public class EmployeeController {
private final EmployeeService service;
public EmployeeController(EmployeeService service) {
this.service = service;
}
@GetMapping
public List<Employee> all() {
return service.getAll();
}
@PostMapping
public Employee add(@RequestBody Employee e) {
return service.save(e);
}
}
7. Test the API
Run Spring Boot:
mvn spring-boot:run
Test endpoints:
# Add employee
curl -X POST http://localhost:8080/employees -H "Content-Type: application/json" -d '{"name":"Alice","role":"Developer"}'
# Get all employees
curl http://localhost:8080/employees
image quote pre code