Spring Data Overview
Spring Data Overview Interview with follow-up questions
1. What is Spring Data and what are its key features?
Spring Data is an umbrella project that simplifies the data-access layer by giving you a consistent, repository-based programming model across many data stores — relational (JPA), MongoDB, Redis, Elasticsearch, R2DBC, etc. You declare a repository interface and Spring Data generates the implementation.
Key features:
- Repository abstraction — extend
JpaRepository/CrudRepositoryand get CRUD for free; no implementation class to write. - Derived query methods —
findByEmailAndStatus(...)is parsed into a query automatically;@Queryfor custom JPQL/SQL. - Pagination & sorting —
Pageable/Sortfor large result sets. - Auditing —
@CreatedDate/@LastModifiedBypopulate automatically. - Projections & derived DTOs, plus Specifications/Querydsl for dynamic queries.
- Consistent model across stores — the same concepts whether it's SQL or NoSQL.
public interface UserRepository extends JpaRepository {
Optional findByEmail(String email);
Page findByActiveTrue(Pageable page);
}
The 2026 framing: Spring Data JPA (on Hibernate) is the most common module; note that current versions run on Jakarta Persistence (jakarta.persistence.*, not javax) under Spring Boot 3+. A useful caveat to mention: derived methods are great for simple cases, but watch for N+1 query problems and overly long method names — drop to @Query/projections when queries get complex.
Follow-up 1
How does Spring Data simplify data access?
Spring Data simplifies data access by providing a consistent programming model and abstraction for interacting with different types of data stores. It eliminates the need for writing boilerplate code for common database operations like creating, reading, updating, and deleting data. Spring Data also reduces the amount of manual query writing by allowing you to define queries using method names. It automatically generates the necessary SQL or NoSQL queries based on the method names. Additionally, Spring Data provides support for pagination and sorting of query results, making it easier to handle large datasets. Overall, Spring Data abstracts away the complexities of data access and provides a more streamlined and efficient way to work with databases.
Follow-up 2
Can you explain the concept of Repository in Spring Data?
In Spring Data, a Repository is an interface that defines a set of methods for interacting with a specific type of data entity. It acts as a mediator between the application and the underlying data store. The Repository interface provides methods for common database operations like creating, reading, updating, and deleting data. These methods can be customized by adding specific query keywords to the method names. The Repository interface is implemented by Spring Data at runtime, which generates the necessary code for executing the database operations based on the method definitions. By using Repositories, developers can abstract away the low-level details of data access and focus on the business logic of the application.
Follow-up 3
What is Spring Data JPA?
Spring Data JPA is a subproject of Spring Data that provides support for JPA (Java Persistence API) based data access. It combines the power of JPA with the convenience of Spring Data, allowing developers to build data access layers for relational databases using a simple and consistent programming model. Spring Data JPA provides a set of interfaces and annotations that extend the JPA specification and add additional functionality. It includes features like automatic CRUD operations, query methods, pagination and sorting, and integration with other Spring projects. With Spring Data JPA, developers can write less boilerplate code and focus more on the business logic of their applications.
Follow-up 4
How does Spring Data support NoSQL databases?
Spring Data provides support for NoSQL databases through its dedicated modules. Each NoSQL database has its own module in Spring Data, which provides the necessary abstractions and implementations for interacting with that specific database. For example, Spring Data MongoDB is the module for MongoDB, Spring Data Redis is the module for Redis, and so on. These modules provide similar features as Spring Data for relational databases, such as automatic CRUD operations, query methods, pagination and sorting, and integration with other Spring projects. By using the appropriate Spring Data module for a specific NoSQL database, developers can easily work with NoSQL databases in a consistent and efficient manner.
2. How does Spring Data integrate with Spring Boot?
Spring Boot makes Spring Data nearly zero-config through auto-configuration and starters:
- Add a starter — e.g.
spring-boot-starter-data-jpa(or-data-mongodb,-data-redis). It pulls in Spring Data, the provider (Hibernate for JPA), and a connection pool (HikariCP). - Auto-configuration detects it on the classpath and configures the infrastructure beans:
DataSource,EntityManagerFactory, and aPlatformTransactionManager— driven by yourapplication.yml(spring.datasource.*,spring.jpa.*). - Repository scanning —
@SpringBootApplicationenables@EnableJpaRepositories, so your repository interfaces are discovered and proxied automatically. You just inject them.
spring.datasource.url: jdbc:postgresql://db:5432/app
spring.jpa.hibernate.ddl-auto: validate
@Service
class UserService {
private final UserRepository users; // injected, fully wired
UserService(UserRepository users) { this.users = users; }
}
Points worth adding: Boot also auto-configures things like an embedded H2 for tests, Flyway/Liquibase migrations if present, and @DataJpaTest slices for fast repository tests. The result is you write the entity + repository interface and Boot handles the rest of the wiring.
Follow-up 1
What are the advantages of using Spring Data with Spring Boot?
There are several advantages of using Spring Data with Spring Boot:
Simplified data access: Spring Data provides a unified and consistent API for accessing different data stores, such as relational databases, NoSQL databases, and more. This simplifies the data access layer and reduces the amount of boilerplate code.
Automatic repository implementation: Spring Data automatically generates the implementation of repository interfaces based on the defined methods. This eliminates the need to write custom repository implementations.
Integration with Spring Boot: Spring Data integrates seamlessly with Spring Boot, leveraging its auto-configuration capabilities. This makes it easy to configure and use Spring Data in a Spring Boot application.
Support for query methods: Spring Data allows developers to define query methods on repository interfaces using a simple naming convention. These query methods are automatically translated into database queries, reducing the need to write complex SQL or JPQL queries.
Follow-up 2
How does Spring Boot auto-configuration work with Spring Data?
Spring Boot auto-configuration works with Spring Data by automatically configuring the necessary beans and repositories based on the data store being used. When Spring Data is included as a dependency in a Spring Boot application, it scans the classpath for the presence of specific Spring Data modules, such as Spring Data JPA or Spring Data MongoDB. It then automatically configures the required beans, such as the EntityManagerFactory for JPA or the MongoTemplate for MongoDB, and sets up the necessary infrastructure to work with the chosen data store.
Spring Boot's auto-configuration is based on a combination of classpath scanning, conditional configuration, and default property values. It uses sensible defaults to configure the beans, but also allows for customization through application.properties or application.yml files.
Overall, Spring Boot's auto-configuration simplifies the setup and configuration of Spring Data in a Spring Boot application, reducing the amount of manual configuration required.
Follow-up 3
Can you explain the role of Spring Data Starter in Spring Boot?
In Spring Boot, a starter is a dependency that includes a set of pre-configured dependencies and settings for a specific purpose. The Spring Data Starter is a special starter that provides the necessary dependencies and auto-configuration for working with Spring Data.
When the Spring Data Starter is included as a dependency in a Spring Boot application, it automatically pulls in the required Spring Data module dependencies, such as Spring Data JPA or Spring Data MongoDB. It also configures the necessary beans and repositories based on the chosen data store.
The Spring Data Starter simplifies the setup and configuration of Spring Data in a Spring Boot application by providing a convenient way to include all the required dependencies and auto-configuration in a single dependency declaration. This reduces the need for manual dependency management and configuration, making it easier to get started with Spring Data in a Spring Boot project.
3. What is the role of Query Methods in Spring Data?
Query methods let you define a query just by naming a repository method — Spring Data parses the name and generates the query at startup, so you write no SQL/JPQL and no implementation:
public interface UserRepository extends JpaRepository {
Optional findByEmail(String email);
List findByStatusAndCreatedAfter(Status status, Instant t);
long countByActiveTrue();
List findTop5ByOrderByCreatedDesc();
}
The parser understands keywords like findBy, And/Or, Between, LessThan, Like, In, OrderBy, Top/First, and True/False. You can also return Page/Slice with a Pageable, or a projection/DTO.
When the derived approach gets unwieldy, you switch to:
@Query— explicit JPQL (or native SQL withnativeQuery = true).@Modifying @Query— for update/delete statements.- Specifications / Querydsl — for dynamic, composable queries.
The points interviewers reward: derived queries are excellent for simple lookups but method names balloon for complex criteria (use @Query instead), and they can hide performance issues (N+1 fetching, missing indexes) — so review the generated SQL (spring.jpa.show-sql / statistics) for hot paths. They're a productivity feature, not a replacement for understanding the queries being run.
Follow-up 1
How do you define a Query Method?
To define a Query Method in Spring Data, you need to follow a specific naming convention. The method name should start with a prefix that indicates the type of operation (e.g., find, get, count, delete). After the prefix, you can specify the properties or fields to be used for filtering or sorting the data. Spring Data will automatically generate the appropriate SQL query based on the method name.
Follow-up 2
Can you give an example of a Query Method?
Sure! Here's an example of a Query Method in Spring Data:
public interface UserRepository extends JpaRepository {
List findByFirstName(String firstName);
}
In this example, the findByFirstName method is defined in the UserRepository interface. It returns a list of User objects filtered by the firstName property. Spring Data will generate the SQL query to retrieve the matching users based on the method name.
Follow-up 3
What are the naming conventions for Query Methods in Spring Data?
The naming conventions for Query Methods in Spring Data are as follows:
- The method name should start with a prefix that indicates the type of operation (e.g., find, get, count, delete).
- After the prefix, you can specify the properties or fields to be used for filtering or sorting the data.
- You can use keywords like
And,Or,Between,LessThan,GreaterThan, etc., to combine multiple conditions.
By following these naming conventions, Spring Data will automatically generate the appropriate SQL query based on the method name.
4. What is the difference between CrudRepository and JpaRepository in Spring Data?
They sit in an inheritance hierarchy, each adding capability:
Repository (marker)
└─ CrudRepository // save, findById, findAll, delete, count
└─ PagingAndSortingRepository // findAll(Pageable), findAll(Sort)
└─ JpaRepository // JPA-specific extras
CrudRepository— basic CRUD, store-agnostic (works for JPA, Mongo, etc.).JpaRepository— JPA-specific and adds:findAll()returningList(notIterable), batch ops (saveAll,deleteAllInBatch),flush()/saveAndFlush(), andgetReferenceById()(lazy proxy). It also inherits paging/sorting.
public interface UserRepository extends JpaRepository {} // CRUD + paging + JPA extras for free
The clarification interviewers want (the source mixes this up): derived query methods like findByEmail come from Spring Data's query-parsing for all repository types, not from JpaRepository specifically — you can declare them on a CrudRepository too. The real difference is that JpaRepository is JPA-bound and adds flush/batch/JPA conveniences. Use JpaRepository for relational/JPA apps; prefer the smaller CrudRepository/PagingAndSortingRepository if you want to stay store-agnostic or expose a narrower API. (In current versions, ListCrudRepository/ListPagingAndSortingRepository offer List-returning variants without going full JPA.)
Follow-up 1
What additional functionalities does JpaRepository provide?
JpaRepository provides additional functionalities compared to CrudRepository. Some of the additional functionalities provided by JpaRepository are:
Query methods: JpaRepository includes methods like findBy, findAllBy, deleteBy, etc. These methods use Spring Data's query generation mechanism to generate queries based on method names. This allows you to easily query and manipulate data without writing explicit queries.
Pagination and sorting: JpaRepository supports pagination and sorting of data. You can use methods like findAll(Pageable pageable) to retrieve data in a paginated manner. This is useful when dealing with large datasets.
Batch operations: JpaRepository provides methods for performing batch operations such as saveAll, deleteAll, etc. This allows you to perform bulk operations on entities.
These additional functionalities make JpaRepository a more powerful interface for working with data in Spring Data.
Follow-up 2
When should one use CrudRepository over JpaRepository?
CrudRepository should be used when you only need the basic CRUD operations on entities and do not require the additional functionalities provided by JpaRepository. If your use case involves simple CRUD operations like save, delete, findById, findAll, etc., then CrudRepository is sufficient.
Using CrudRepository has the advantage of being more lightweight and having a simpler API compared to JpaRepository. It is also more generic and can be used with any entity type.
However, if you need to perform more complex queries, pagination, sorting, or batch operations, then JpaRepository is the better choice. It provides additional methods and functionalities that can simplify your code and improve performance.
Follow-up 3
Can you explain the concept of PagingAndSortingRepository in Spring Data?
PagingAndSortingRepository is an interface provided by Spring Data that extends CrudRepository and adds support for pagination and sorting of data.
With PagingAndSortingRepository, you can retrieve data in a paginated manner and specify the sorting order of the results. It provides methods like findAll(Pageable pageable) that accept a Pageable object as a parameter.
The Pageable object allows you to specify the page number, page size, and sorting criteria. You can create a Pageable object using PageRequest.of(pageNumber, pageSize, Sort sort), where pageNumber is the zero-based page number, pageSize is the number of items per page, and Sort is the sorting criteria.
PagingAndSortingRepository is useful when dealing with large datasets and when you need to display data in a paginated manner. It simplifies the process of retrieving data in chunks and allows you to control the sorting order of the results.
5. How does Spring Data handle transactions?
Spring Data builds on Spring's transaction management, so you control transactions declaratively with @Transactional, and the underlying PlatformTransactionManager (e.g. JpaTransactionManager) handles commit/rollback via AOP proxies.
Two things specific to Spring Data JPA worth knowing:
- Repository CRUD methods are already transactional — the SimpleJpaRepository methods (
save,delete, etc.) carry@Transactional(writes are read-write; query methods arereadOnly). So a single repository call is atomic out of the box. - For multi-step business operations, annotate the service method
@Transactionalso several repository calls commit/rollback together as one unit.
@Service
class TransferService {
@Transactional // both saves commit or roll back together
public void transfer(Long from, Long to, BigDecimal amt) {
accounts.debit(from, amt);
accounts.credit(to, amt);
}
}
The gotchas interviewers probe: @Transactional only works on calls through the Spring proxy — self-invocation bypasses it, and by default it rolls back on unchecked exceptions only (set rollbackFor for checked ones). Use readOnly = true for query-only methods (a performance hint), and understand propagation (REQUIRED default, REQUIRES_NEW, etc.). So Spring Data doesn't reinvent transactions — it leans on Spring's @Transactional, adding sensible defaults at the repository level.
Follow-up 1
What is the @Transactional annotation and how is it used in Spring Data?
The @Transactional annotation is used to define the transactional behavior of a method in Spring Data. It can be applied to both methods and classes. When applied to a method, it indicates that the method should be executed within a transaction. When applied to a class, it indicates that all methods within that class should be executed within a transaction. The @Transactional annotation can also be used with additional attributes to customize the transactional behavior, such as propagation, isolation level, and rollback rules.
Follow-up 2
How does Spring Data ensure data consistency?
Spring Data ensures data consistency by using the transaction management capabilities provided by the Spring Framework. When a method annotated with @Transactional is executed, Spring Data will start a new transaction if one does not already exist. It will then execute the method within that transaction, ensuring that any changes made to the data are consistent. If an exception is thrown during the execution of the method, Spring Data will automatically roll back the transaction, undoing any changes made to the data.
Follow-up 3
Can you explain the concept of Propagation in Spring Data transactions?
Propagation is a concept in Spring Data transactions that determines how transactions should be propagated from one method to another. The @Transactional annotation provides several propagation options, such as REQUIRED, REQUIRES_NEW, SUPPORTS, and NOT_SUPPORTED.
- REQUIRED: If a transaction already exists, the method will execute within that transaction. If no transaction exists, a new transaction will be created.
- REQUIRES_NEW: A new transaction will always be created, even if a transaction already exists.
- SUPPORTS: If a transaction already exists, the method will execute within that transaction. If no transaction exists, the method will execute without a transaction.
- NOT_SUPPORTED: The method will execute without a transaction, even if a transaction already exists.
Live mock interview
Mock interview: Spring Data Overview
- Read your scene and goals
- Talk it out; goals tick off live
- Get a score and stronger lines
Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.