The data from the previous lesson disappears when the server stops. Here it is stored in a database. Spring Data JPA turns Java classes into tables and writes the SQL queries itself – it is enough to write an interface. At the end we explain how the application is packaged and put on the internet.
Before you start: what you need to know first – REST API, the same ideas in Django (model, migrations). How to learn: work in your own project step by step, and after each step start the server and check the result in the browser. The examples are for Spring Boot 3 or 4 and Java 17+; type each piece of code into the file named in the comment at the top of the example.
Adding libraries
On start.spring.io (or in IntelliJ: right-click on pom.xml → Add Dependency) two more dependencies are added:
Dependency
What it gives
Spring Data JPA
working with a database through Java classes (Hibernate)
H2 Database
a small database written in Java; it is stored in a file in the project folder – nothing is installed
Later H2 is easily replaced by a PostgreSQL or MySQL database – only the dependency and the settings change, the code stays the same.
# src/main/resources/application.properties
spring.application.name=tasks
# the database in the file ./data/tasks.mv.db (it is created by itself)
spring.datasource.url=jdbc:h2:file:./data/tasks
spring.datasource.username=sa
spring.datasource.password=
# Hibernate creates and changes the tables according to the classes
spring.jpa.hibernate.ddl-auto=update
# SQL queries are printed in the console – useful for learning
spring.jpa.show-sql=true
The entity: a class that becomes a table
The Task class gets the @Entity annotation. The field with @Id is the primary key, and @GeneratedValue means that the database assigns the numbers itself. The getters, setters and the empty constructor stay as in the previous lesson:
// src/main/java/rs/svetprogramiranja/tasks/Task.java
package rs.svetprogramiranja.tasks;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import java.time.LocalDate;
@Entity // the TASK table
public class Task {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, length = 200)
private String title;
private String subject;
private LocalDate dueDate;
private boolean done;
public Task() { }
public Task(String title, String subject, LocalDate dueDate) {
this.title = title;
this.subject = subject;
this.dueDate = dueDate;
}
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
public String getSubject() { return subject; }
public void setSubject(String subject) { this.subject = subject; }
public LocalDate getDueDate() { return dueDate; }
public void setDueDate(LocalDate dueDate) { this.dueDate = dueDate; }
public boolean isDone() { return done; }
public void setDone(boolean done) { this.done = done; }
}
When the application starts, Hibernate creates the table (you can see create table task (...) in the console). Each object is one row of the table, and each field one column.
The repository: an interface without code
To access a table it is enough to write an interface that extends JpaRepository<Task, Long> (the entity type and the key type). When the application starts, Spring itself creates a class that implements it. You get ready-made methods findAll, findById, save, deleteById, count…, and new ones are added just by the method's name:
// src/main/java/rs/svetprogramiranja/tasks/TaskRepository.java
package rs.svetprogramiranja.tasks;
import java.time.LocalDate;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
public interface TaskRepository extends JpaRepository<Task, Long> {
// Spring makes a query from the method name:
// SELECT * FROM task WHERE done = false ORDER BY due_date
List<Task> findByDoneFalseOrderByDueDateAsc();
// WHERE upper(subject) = upper(?)
List<Task> findBySubjectIgnoreCase(String subject);
// WHERE upper(title) LIKE upper('%' || ? || '%')
List<Task> findByTitleContainingIgnoreCase(String part);
// WHERE due_date < ? AND done = false
long countByDueDateBeforeAndDoneFalse(LocalDate date);
}
Part of the name
Meaning in the query
findBy… / countBy…
SELECT / SELECT COUNT
…And…, …Or…
several conditions
Containing, StartingWith
LIKE '%x%', LIKE 'x%'
Before, After, GreaterThan
<, >
IgnoreCase
regardless of upper and lower case
OrderBy…Asc/Desc
ORDER BY
A service that uses the database
The service now uses the repository instead of a map. The controller from the previous lesson stays exactly the same – that is the benefit of splitting the code into layers.
// src/main/java/rs/svetprogramiranja/tasks/TaskService.java
package rs.svetprogramiranja.tasks;
import java.util.List;
import java.util.Optional;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
@Service
public class TaskService {
private final TaskRepository repo;
public TaskService(TaskRepository repo) {
this.repo = repo;
}
public List<Task> all() {
return repo.findAll(Sort.by("dueDate")); // SELECT ... ORDER BY due_date
}
public Optional<Task> find(long id) {
return repo.findById(id);
}
public Task add(Task t) {
t.setId(null); // the database assigns the id
return repo.save(t); // INSERT
}
public Optional<Task> update(long id, Task changed) {
return repo.findById(id).map(t -> {
t.setTitle(changed.getTitle());
t.setSubject(changed.getSubject());
t.setDueDate(changed.getDueDate());
t.setDone(changed.isDone());
return repo.save(t); // UPDATE
});
}
public boolean delete(long id) {
if (!repo.existsById(id)) return false;
repo.deleteById(id); // DELETE
return true;
}
public List<Task> search(String part) {
return repo.findByTitleContainingIgnoreCase(part);
}
}
Start the server, add a few tasks, stop the server and start it again – the tasks are still there. The file data/tasks.mv.db has appeared in the project folder.
Starting data and searching
A class that implements CommandLineRunner and is marked with @Component runs once, after the application starts – handy for putting examples into an empty database:
// src/main/java/rs/svetprogramiranja/tasks/StartupData.java
package rs.svetprogramiranja.tasks;
import java.time.LocalDate;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class StartupData implements CommandLineRunner {
private final TaskRepository repo;
public StartupData(TaskRepository repo) {
this.repo = repo;
}
@Override
public void run(String... args) {
if (repo.count() == 0) { // only when the database is empty
repo.save(new Task("Do exercises 1-5", "Maths", LocalDate.now().plusDays(2)));
repo.save(new Task("Read the set book", "English", LocalDate.now().plusDays(7)));
repo.save(new Task("Learn Newton's laws", "Physics", LocalDate.now().plusDays(4)));
}
}
}
Searching through the API: a method that calls service.search is added to the controller:
// an addition in the TaskController class
// import org.springframework.web.bind.annotation.RequestParam;
// http://localhost:8080/api/tasks/search?q=read
@GetMapping("/search")
public List<Task> search(@RequestParam String q) {
return service.search(q);
}
Packaging and putting the application on the internet
The whole application is packaged into one .jar file, which runs on any computer with Java:
To put the application on the internet, you use services that run Java applications or Docker containers (e.g. Render, Railway, Fly.io). Most often a Dockerfile like this in the root of the project is enough:
# Dockerfile – first the application is built, then only the .jar is copied into a smaller image
FROM eclipse-temurin:21-jdk AS build
WORKDIR /app
COPY . .
RUN chmod +x mvnw && ./mvnw -q clean package -DskipTests
FROM eclipse-temurin:21-jre
WORKDIR /app
COPY --from=build /app/target/*.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]
On such services the disk is usually wiped with every new deployment, so an H2 database in a file is not good for real use – then you use a PostgreSQL database offered by the service, and the settings are given through environment variables (SPRING_DATASOURCE_URL, SPRING_DATASOURCE_USERNAME, SPRING_DATASOURCE_PASSWORD). The same process with Python and Django is described in the lesson Putting it on the internet.
Practice tasks
Each task has a hint and a solution.
TASK 01Difficulty: harder
Subjects and tasks
Add a Subject entity (fields: id, name, teacher) with a repository, and a link: every task belongs to one subject (a many-to-one relationship). Add the route GET /api/subjects/{id}/tasks that returns the tasks of that subject, sorted by due date.
Hint
In the Task class add the field private Subject subjectObj; with the @ManyToOne annotation. In TaskRepository add the method findBySubjectObjIdOrderByDueDateAsc(Long subjectId) – Spring also understands a path through a link (SubjectObj → Id).
Solution (Java)
// src/main/java/rs/svetprogramiranja/tasks/Subject.java
package rs.svetprogramiranja.tasks;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
public class Subject {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String teacher;
public Subject() { }
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getTeacher() { return teacher; }
public void setTeacher(String teacher) { this.teacher = teacher; }
}
// src/main/java/rs/svetprogramiranja/tasks/SubjectRepository.java
package rs.svetprogramiranja.tasks;
import org.springframework.data.jpa.repository.JpaRepository;
public interface SubjectRepository extends JpaRepository<Subject, Long> { }
// an addition in the Task class (+ a getter and setter for subjectObj)
// import jakarta.persistence.ManyToOne;
@ManyToOne // many tasks – one subject (the column subject_obj_id)
private Subject subjectObj;
// an addition in TaskRepository
List<Task> findBySubjectObjIdOrderByDueDateAsc(Long subjectId);
// src/main/java/rs/svetprogramiranja/tasks/SubjectController.java
package rs.svetprogramiranja.tasks;
import java.util.List;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/subjects")
public class SubjectController {
private final SubjectRepository subjects;
private final TaskRepository tasks;
public SubjectController(SubjectRepository subjects, TaskRepository tasks) {
this.subjects = subjects;
this.tasks = tasks;
}
@GetMapping
public List<Subject> all() {
return subjects.findAll();
}
@GetMapping("/{id}/tasks")
public ResponseEntity<List<Task>> tasksOfSubject(@PathVariable long id) {
if (!subjects.existsById(id))
return ResponseEntity.notFound().build();
return ResponseEntity.ok(tasks.findBySubjectObjIdOrderByDueDateAsc(id));
}
}
Common mistakes and tips
If the entity class changes, ddl-auto=update adds new columns but does not delete old ones; for a clean start delete the database file in the data folder.
The method name in the repository must match the field names exactly (findByTitle… for the field title), otherwise the application will not even start.
Do not write database passwords in code that you publish (GitHub) – give them through environment variables.
For real applications with user accounts, Spring Security is used – do not make your own way of storing passwords.
Check your knowledge
Open the quiz
Spring Data JPA
1. What does the @Entity annotation mean?
2. Who writes the class that implements the TaskRepository interface?
3. Which operation does repo.save(t) perform for a new object?
4. Why did the controller not change when the database was added?
Podešavanja kolačića
Koristimo kolačiće da bismo vam pružili najbolje moguće iskustvo. Takođe nam omogućavaju da analiziramo ponašanje korisnika kako bismo stalno poboljšavali veb lokaciju za vas.