Spring Data JPA
Spring Data JPA lets you read and write database tables by declaring a Java interface; Spring writes the implementation for you at startup. You get save, find, delete, paging and sorting for free, and you can add queries just by naming methods such as findByCategory. Under the hood it still uses JPA and Hibernate, so everything from the Java JPA lesson applies, but most of the EntityManager code disappears.
This lesson uses Spring Boot 4.1 with Hibernate 7 and an in-memory H2 database, so every example runs without installing a database server.
Spring Data JPA Repository Interfaces
| Interface | Adds |
|---|---|
Repository<T, ID> | Marker only; you declare every method yourself |
CrudRepository<T, ID> | save, findById, findAll, count, deleteById, existsById |
ListCrudRepository<T, ID> | Same as above but returns List instead of Iterable |
PagingAndSortingRepository<T, ID> | findAll(Sort), findAll(Pageable) |
JpaRepository<T, ID> | All of the above plus saveAll, flush, saveAndFlush, deleteAllInBatch |
How it works:
Tis the entity class andIDis the type of its@Idfield.- Most applications extend
JpaRepository, which inherits everything in the table. The generated class is a normal Spring bean that you inject with constructor injection, as in the Spring Boot tutorial.
Set Up Spring Data JPA With H2
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
# src/main/resources/application.properties
spring.datasource.url=jdbc:h2:mem:coursedb
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.show-sql=false
How it works:
- The JPA starter brings Hibernate, Spring Data JPA, the HikariCP connection pool and transaction support. Spring Boot auto-configures the
DataSource,EntityManagerFactoryand transaction manager from the URL. ddl-auto=create-dropmakes Hibernate create tables from your entities at startup and drop them at shutdown. That is ideal for learning and tests; production databases usevalidateornonewith a migration tool such as Flyway.- To use MySQL or PostgreSQL later, change the driver dependency and the three
spring.datasource.*properties (URL, username, password). The Java code stays the same.
Map an Entity Class
package com.gocourse.data.course;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
public class Course {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, unique = true, length = 40)
private String code;
@Column(nullable = false)
private String title;
private String category;
private int feeInr;
private int seats;
protected Course() {} // required by JPA
public Course(String code, String title, String category, int feeInr, int seats) {
this.code = code;
this.title = title;
this.category = category;
this.feeInr = feeInr;
this.seats = seats;
}
public Long getId() { return id; }
public String getCode() { return code; }
public String getTitle() { return title; }
public String getCategory() { return category; }
public int getFeeInr() { return feeInr; }
public int getSeats() { return seats; }
public void setFeeInr(int feeInr) { this.feeInr = feeInr; }
public void setSeats(int seats) { this.seats = seats; }
@Override
public String toString() {
return code + " (" + feeInr + ")";
}
}
How it works:
@Entitymaps the class to a table namedcourse. Spring Boot's naming strategy turnsfeeInrinto the columnfee_inr.IDENTITYlets the database generate ids1, 2, 3.... The protected no-argument constructor is used by Hibernate when it loads rows; your code uses the full constructor.- Entities are mutable classes, not records, because Hibernate changes their fields and tracks those changes.
Create a Repository and Do CRUD
package com.gocourse.data.course;
import org.springframework.data.jpa.repository.JpaRepository;
public interface CourseRepository extends JpaRepository<Course, Long> {
}
package com.gocourse.data;
import com.gocourse.data.course.Course;
import com.gocourse.data.course.CourseRepository;
import java.util.List;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
@Configuration
public class CrudDemo {
@Bean
@Order(1)
CommandLineRunner crud(CourseRepository courses) {
return args -> {
// CREATE
Course java = courses.save(new Course("java", "Java Programming", "backend", 4999, 30));
courses.saveAll(List.of(
new Course("go", "Go Language", "backend", 2999, 20),
new Course("html", "HTML and CSS", "web", 1999, 40),
new Course("react", "React Basics", "web", 3499, 25),
new Course("spring", "Spring Boot", "backend", 5999, 2)));
System.out.println("Saved java with id " + java.getId() + ", total " + courses.count());
// READ
System.out.println("Course 2: " + courses.findById(2L).map(Course::getTitle).orElse("none"));
System.out.println("All: " + courses.findAll());
// UPDATE: change the object, then save it again
java.setFeeInr(4499);
courses.save(java);
System.out.println("Java fee now " + courses.findById(java.getId()).orElseThrow().getFeeInr());
// DELETE
Course temp = courses.save(new Course("temp", "Temporary", "test", 1, 1));
courses.deleteById(temp.getId());
System.out.println("Temp exists? " + courses.existsById(temp.getId()) + ", total " + courses.count());
};
}
}
Output:
Saved java with id 1, total 5
Course 2: Go Language
All: [java (4999), go (2999), html (1999), react (3499), spring (5999)]
Java fee now 4499
Temp exists? false, total 5
With spring.jpa.show-sql=true, Hibernate also prints each statement, for example:
Hibernate: insert into course (category,code,fee_inr,seats,title,id) values (?,?,?,?,?,default)
How it works:
- You never wrote a class implementing
CourseRepository. Spring Data creates a proxy at startup and backs each method with JPA calls. saveinserts a new entity (no id yet) or merges an existing one. It returns the saved entity with its generated id.findByIdreturns anOptional, so a missing row is handled withoutnull.- Every repository method runs in its own transaction by default, so each call above commits immediately.
Note: The SQL text differs between Hibernate versions and databases. Use
show-sqlonly while learning; in real projects setlogging.level.org.hibernate.SQL=debugso SQL goes through the normal logger.
Derived Query Methods
Spring Data reads a method name, splits it into parts and builds the query. findByCategory(String category) becomes select c from Course c where c.category = ?1.
| Keyword | Example method | Generated condition |
|---|---|---|
And, Or | findByCategoryAndFeeInrLessThan | category = ? and fee_inr < ? |
LessThan, GreaterThanEqual | findByFeeInrGreaterThanEqual | fee_inr >= ? |
Between | findByFeeInrBetween(min, max) | fee_inr between ? and ? |
Containing, StartingWith | findByTitleContaining | title like %?% |
IgnoreCase | findByCodeIgnoreCase | upper(code) = upper(?) |
In | findByCodeIn(List<String>) | code in (...) |
OrderBy...Asc/Desc | findByCategoryOrderByTitle | order by title |
Top, First | findTop2ByOrderByFeeInrDesc | limit 2 |
countBy, existsBy, deleteBy | countByCategory | count / exists / delete |
package com.gocourse.data.course;
import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
public interface CourseRepository extends JpaRepository<Course, Long> {
Optional<Course> findByCode(String code);
List<Course> findByCategoryOrderByTitle(String category);
List<Course> findByFeeInrLessThanOrderByFeeInrAsc(int maxFee);
List<Course> findByTitleContainingIgnoreCaseOrderByTitle(String text);
long countByCategory(String category);
boolean existsByCode(String code);
List<Course> findTop2ByOrderByFeeInrDesc();
}
@Bean
@Order(2)
CommandLineRunner derivedQueries(CourseRepository courses) {
return args -> {
System.out.println("Web courses: " + courses.findByCategoryOrderByTitle("web"));
System.out.println("Under 3500: " + courses.findByFeeInrLessThanOrderByFeeInrAsc(3500));
System.out.println("Title has 'ING': " + courses.findByTitleContainingIgnoreCaseOrderByTitle("ING"));
System.out.println("Backend count: " + courses.countByCategory("backend"));
System.out.println("Python exists? " + courses.existsByCode("python"));
System.out.println("Two most expensive: " + courses.findTop2ByOrderByFeeInrDesc());
System.out.println("By code: " + courses.findByCode("go").map(Course::getTitle).orElse("-"));
};
}
Output:
Web courses: [html (1999), react (3499)]
Under 3500: [html (1999), go (2999), react (3499)]
Title has 'ING': [java (4499), spring (5999)]
Backend count: 3
Python exists? false
Two most expensive: [spring (5999), java (4499)]
By code: Go Language
How it works:
- Property names in the method must match entity field names (
feeInr), not column names (fee_inr). - Spring Data checks every method name at startup. A typo such as
findByFeefails immediately with a clear error instead of at runtime. IgnoreCasemade"ING"match both "Java Programming" and "Spring Boot".- Long names are fine for two or three conditions. Beyond that, switch to
@Query.
Write Custom Queries With @Query
@Query takes JPQL (queries on entities) or native SQL (queries on tables). Bulk updates also need @Modifying.
// add to CourseRepository
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;
@Query("select c from Course c where c.seats > 0 and c.feeInr <= :budget order by c.feeInr")
List<Course> findAvailableWithinBudget(@Param("budget") int budget);
@Query(value = "select category, count(*) from course group by category order by category",
nativeQuery = true)
List<Object[]> countPerCategory();
@Modifying(clearAutomatically = true)
@Transactional
@Query("update Course c set c.feeInr = c.feeInr - :discount where c.category = :category")
int discountCategory(@Param("category") String category, @Param("discount") int discount);
@Bean
@Order(3)
CommandLineRunner customQueries(CourseRepository courses) {
return args -> {
System.out.println("Within 5000: " + courses.findAvailableWithinBudget(5000));
for (Object[] row : courses.countPerCategory()) {
System.out.println(" " + row[0] + " -> " + row[1]);
}
int changed = courses.discountCategory("web", 500);
System.out.println("Discounted " + changed + " web courses: " + courses.findByCategoryOrderByTitle("web"));
};
}
Output:
Within 5000: [html (1999), go (2999), react (3499), java (4499)]
backend -> 3
web -> 2
Discounted 2 web courses: [html (1499), react (2999)]
How it works:
- JPQL uses the entity and field names (
Course,c.feeInr), so it works on any database. Named parameters such as:budgetare bound with@Param. nativeQuery = truesends the SQL as written, using the table and column names. Use it for database-specific features; the result here comes back asObject[]rows.- An update query must be marked
@Modifyingand run in a transaction.clearAutomatically = trueclears Hibernate's cache of loaded entities afterwards, so the next query sees the new fees instead of stale objects.
Paging and Sorting Results
Loading thousands of rows at once is slow. Pageable asks the database for one page at a time.
@Bean
@Order(4)
CommandLineRunner paging(CourseRepository courses) {
return args -> {
Pageable firstPage = PageRequest.of(0, 2, Sort.by("feeInr").descending());
Page<Course> page = courses.findAll(firstPage);
System.out.println("Page " + (page.getNumber() + 1) + " of " + page.getTotalPages()
+ ": " + page.getContent());
System.out.println("Total rows: " + page.getTotalElements() + ", has next? " + page.hasNext());
Page<Course> next = courses.findAll(page.nextPageable());
System.out.println("Page " + (next.getNumber() + 1) + ": " + next.getContent());
System.out.println("Sorted by title: "
+ courses.findAll(Sort.by("category").and(Sort.by("title"))));
};
}
Output:
Page 1 of 3: [spring (5999), java (4499)]
Total rows: 5, has next? true
Page 2: [react (2999), go (2999)]
Sorted by title: [go (2999), java (4499), spring (5999), html (1499), react (2999)]
How it works:
PageRequest.of(0, 2, sort)means page index 0 (the first page), 2 rows per page. Spring Data addsorder by,offsetandlimitto the SQL and runs a secondcountquery for the totals.nextPageable()builds the request for the following page, which is how "Next" buttons in a Spring MVC page are usually wired.reactandgoboth cost 2999 after the discount, so their order within page 2 is not guaranteed. Add a second sort key, such asSort.by("feeInr").descending().and(Sort.by("code")), when the order must be stable.- Derived queries accept paging too:
Page<Course> findByCategory(String category, Pageable pageable).
Map Relationships With @ManyToOne
An enrollment belongs to one course; a course has many enrollments.
package com.gocourse.data.enrollment;
import com.gocourse.data.course.Course;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import java.time.LocalDate;
@Entity
public class Enrollment {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String studentEmail;
@ManyToOne(optional = false, fetch = FetchType.LAZY)
@JoinColumn(name = "course_id")
private Course course;
private LocalDate enrolledOn;
protected Enrollment() {}
public Enrollment(String studentEmail, Course course, LocalDate enrolledOn) {
this.studentEmail = studentEmail;
this.course = course;
this.enrolledOn = enrolledOn;
}
public Long getId() { return id; }
public String getStudentEmail() { return studentEmail; }
public Course getCourse() { return course; }
public LocalDate getEnrolledOn() { return enrolledOn; }
}
package com.gocourse.data.enrollment;
import java.util.List;
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.jpa.repository.JpaRepository;
public interface EnrollmentRepository extends JpaRepository<Enrollment, Long> {
@EntityGraph(attributePaths = "course") // load the course in the same query
List<Enrollment> findByStudentEmailOrderById(String studentEmail);
long countByCourseCode(String courseCode); // nested property: course.code
boolean existsByStudentEmailAndCourseCode(String studentEmail, String courseCode);
}
How it works:
@ManyToOneadds acourse_idforeign key column to theenrollmenttable.LAZYmeans the course is not loaded until it is needed.countByCourseCodewalks fromEnrollmentintocourse.code, and Spring Data generates the join for you.- Reading a lazy
courseafter the transaction has ended throwsLazyInitializationException, a problem explained in the Java Hibernate lesson.@EntityGraphfixes it for this method by fetching the course with a join in the same query.
Real-World Example: Spring Data JPA With @Transactional Enrollment
Enrolling a student touches two tables: it reduces the course's seats and inserts an enrollment. Both changes must succeed together or not at all, which is the job of @Transactional.
package com.gocourse.data.enrollment;
import com.gocourse.data.course.Course;
import com.gocourse.data.course.CourseRepository;
import java.time.LocalDate;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class EnrollmentService {
private final CourseRepository courses;
private final EnrollmentRepository enrollments;
public EnrollmentService(CourseRepository courses, EnrollmentRepository enrollments) {
this.courses = courses;
this.enrollments = enrollments;
}
@Transactional
public Enrollment enroll(String email, String courseCode) {
Course course = courses.findByCode(courseCode)
.orElseThrow(() -> new IllegalArgumentException("Unknown course " + courseCode));
if (enrollments.existsByStudentEmailAndCourseCode(email, courseCode)) {
throw new IllegalStateException(email + " is already in " + courseCode);
}
if (course.getSeats() <= 0) {
throw new IllegalStateException(course.getTitle() + " is full");
}
course.setSeats(course.getSeats() - 1); // no save() needed: changes are flushed at commit
return enrollments.save(new Enrollment(email, course, LocalDate.now()));
}
@Transactional // all courses or none
public void enrollAll(String email, List<String> courseCodes) {
for (String code : courseCodes) {
enroll(email, code);
}
}
@Transactional(readOnly = true)
public List<String> coursesOf(String email) {
return enrollments.findByStudentEmailOrderById(email).stream()
.map(enrollment -> enrollment.getCourse().getTitle())
.toList();
}
}
@Bean
@Order(5)
CommandLineRunner enrollmentDemo(EnrollmentService service, CourseRepository courses,
EnrollmentRepository enrollments) {
return args -> {
tryEnroll(service, "asha@example.com", "spring");
tryEnroll(service, "ravi@example.com", "spring");
tryEnroll(service, "meena@example.com", "spring"); // no seats left
tryEnroll(service, "asha@example.com", "java");
tryEnroll(service, "asha@example.com", "java"); // duplicate
try {
service.enrollAll("meena@example.com", List.of("go", "spring"));
} catch (IllegalStateException e) {
System.out.println("enrollAll failed: " + e.getMessage());
}
System.out.println("Go enrollments: " + enrollments.countByCourseCode("go")
+ ", Go seats: " + courses.findByCode("go").orElseThrow().getSeats());
System.out.println("Asha's courses: " + service.coursesOf("asha@example.com"));
};
}
static void tryEnroll(EnrollmentService service, String email, String code) {
try {
Enrollment saved = service.enroll(email, code);
System.out.println("Enrolled " + email + " in " + code + " (enrollment #" + saved.getId() + ")");
} catch (IllegalStateException | IllegalArgumentException e) {
System.out.println("Rejected: " + e.getMessage());
}
}
Output:
Enrolled asha@example.com in spring (enrollment #1)
Enrolled ravi@example.com in spring (enrollment #2)
Rejected: Spring Boot is full
Enrolled asha@example.com in java (enrollment #3)
Rejected: asha@example.com is already in java
enrollAll failed: Spring Boot is full
Go enrollments: 0, Go seats: 20
Asha's courses: [Spring Boot, Java Programming]
How it works:
- Dirty checking. Inside the transaction,
courseis a managed entity. Changing its seats with a setter is enough; Hibernate detects the change and issues anUPDATEwhen the transaction commits. - Atomic rollback. In
enrollAll, Meena's Go enrollment was inserted and Go's seats dropped to 19. When the Spring Boot course turned out to be full, theIllegalStateExceptionrolled back the whole transaction, so Go still has 20 seats and 0 enrollments. By default Spring rolls back on unchecked exceptions; addrollbackFor = Exception.classfor checked ones. - One transaction for nested calls.
enrollAllcallsenrollon the same object, so both run inenrollAll's transaction.@Transactionalonenrollmatters only when other beans call it directly. - Read-only transactions.
coursesOfusesreadOnly = true, which lets Hibernate skip change tracking. The@EntityGraphon the repository loads each course in the same query, sogetCourse().getTitle()works without a lazy-loading error. - Business rules in the service. The repositories only fetch and store data. Rules such as "no duplicates" and "no overbooking" live in the service, which a REST controller or Spring MVC page can call. With Spring Data JPA, the whole data layer of this example is two interfaces, two entities and one service.