- Replies:
- 0
- Words:
- 5633

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>
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 runs Derby in embedded in-memory mode.
import jakarta.persistence.*;
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
private String author;
// getters and setters
}
import org.springframework.data.jpa.repository.JpaRepository;
public interface BookRepository extends JpaRepository<Book, Long> {
}
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/books")
public class BookController {
private final BookRepository repo;
public BookController(BookRepository repo) {
this.repo = repo;
}
@PostMapping
public Book create(@RequestBody Book book) {
return repo.save(book);
}
@GetMapping
public List<Book> readAll() {
return repo.findAll();
}
@GetMapping("/{id}")
public Book readOne(@PathVariable Long id) {
return repo.findById(id).orElse(null);
}
@PutMapping("/{id}")
public Book update(@PathVariable Long id, @RequestBody Book book) {
book.setId(id);
return repo.save(book);
}
@DeleteMapping("/{id}")
public void delete(@PathVariable Long id) {
repo.deleteById(id);
}
}
mvn spring-boot:run
Examples:
# Create
curl -X POST http://localhost:8080/books -H "Content-Type: application/json" -d '{"title":"Derby Basics","author":"Alice"}'
# Read
curl http://localhost:8080/books
# Update
curl -X PUT http://localhost:8080/books/1 -H "Content-Type: application/json" -d '{"title":"Derby Advanced","author":"Alice"}'
# Delete
curl -X DELETE http://localhost:8080/books/1
image quote pre code