This guide shows how to use
Apache Derby in
embedded mode with
Spring Boot, where the database runs inside the application.
1. Add Dependency
In
pom.xml
:
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derby</artifactId>
<scope>runtime</scope>
</dependency>
2. Configure Database
In
application.properties
:
spring.datasource.url=jdbc:derby:memory:demoDB;create=true
spring.datasource.driver-class-name=org.apache.derby.jdbc.EmbeddedDriver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=create
jdbc:derby:memory:demoDB;create=true
→ creates an in-memory DB.
ddl-auto=create
→ generates schema on startup.
3. Create Entity
import jakarta.persistence.*;
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private double price;
// getters and setters
}
4. Repository
import org.springframework.data.jpa.repository.JpaRepository;
public interface ProductRepository extends JpaRepository<Product, Long> {
}
5. REST Controller
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/products")
public class ProductController {
private final ProductRepository repo;
public ProductController(ProductRepository repo) {
this.repo = repo;
}
@PostMapping
public Product add(@RequestBody Product product) {
return repo.save(product);
}
@GetMapping
public List<Product> all() {
return repo.findAll();
}
}
6. Test the App
Run Spring Boot:
mvn spring-boot:run
Test with curl:
curl -X POST http://localhost:8080/products -H "Content-Type: application/json" -d '{"name":"Laptop","price":1200}'
curl http://localhost:8080/products
image quote pre code