Spring Data & JPA practice questions

From Spring Certified Professional (Develop) (2V0-72.22) · 17 questions on this topic

Spring Data & JPA practice questions from Spring Certified Professional (Develop) (2V0-72.22). This pack has 17 questions tagged Spring Data & JPA, drawn from its timed mock exams. 8 of them are worked through in full below — the question, every option, why each is right or wrong, and the explanation.

Worked examples for Spring Data & JPA

  1. Question 1

    With spring-boot-starter-data-jpa on the classpath and an embedded database present, what does Spring Boot auto-configure?

    1. A. A DataSource, an EntityManagerFactory, a JpaTransactionManager, and Spring Data repository scanningCorrect answer

      The JPA starter auto-configures the full stack — an embedded DataSource, a JPA EntityManagerFactory (Hibernate by default), a JpaTransactionManager, and scanning for Spring Data repository interfaces — so a basic app needs no manual wiring.

    2. B. Only a DataSource; the EntityManagerFactory must be declared manually

      Understates auto-configuration: the EntityManagerFactory is auto-configured as well, not something you must declare by hand.

    3. C. A JdbcTemplate but no JPA infrastructure

      Names the wrong infrastructure: the JPA starter configures JPA components such as the EntityManagerFactory and transaction manager, not merely a JdbcTemplate.

    4. D. Nothing — JPA always requires a hand-written persistence.xml and manual wiring

      Denies auto-configuration entirely: Boot's auto-configuration removes the need for a hand-written persistence.xml and manual wiring in a basic app.

    Explanation

    With the JPA starter and an embedded database on the classpath, Spring Boot auto-configures the entire persistence stack — a DataSource, a JPA EntityManagerFactory backed by Hibernate, a JpaTransactionManager, and scanning for Spring Data repository interfaces. A basic application therefore runs without any hand-written persistence.xml or manual bean wiring.

  2. Question 2

    Which TWO statements about Spring Boot's Spring Data JPA auto-configuration are correct? Select TWO.

    1. A. spring.jpa.open-in-view defaults to true, keeping the persistence context open for the duration of a web request so lazy associations can still be initialized during view rendering.Correct answer

      Boot enables Open EntityManager in View by default (open-in-view=true), which holds the persistence context open across the request and lets lazy associations load during rendering.

    2. B. spring.jpa.hibernate.ddl-auto=validate creates any missing tables so the schema matches the entities.

      validate only checks that the existing schema matches the entity mappings; it never creates or alters tables.

    3. C. Repository interfaces are bootstrapped automatically by the starter, so a basic application needs no explicit @EnableJpaRepositories.Correct answer

      The JPA starter's auto-configuration scans for and proxies Spring Data repository interfaces automatically, so @EnableJpaRepositories is not required in a standard layout.

    4. D. spring.jpa.show-sql requires an external log configuration file, without which JPA cannot emit SQL at all.

      show-sql simply toggles printing of the generated SQL and needs no external file to work.

    5. E. The EntityManagerFactory must be declared as an explicit @Bean because the starter only configures the DataSource.

      The starter auto-configures the EntityManagerFactory (backed by Hibernate) along with the DataSource, so no manual bean is needed.

    Explanation

    Two facts hold for the JPA starter: Open EntityManager in View is on by default so the persistence context spans the whole request, and repository interfaces are bootstrapped automatically without an explicit enabling annotation. The distractors misstate the ddl-auto=validate mode (it checks rather than creates), the show-sql toggle (no external file needed), and the auto-configured EntityManagerFactory (which the starter provides for you).

  3. Question 3

    When a derived method name cannot express the query you need, what is the standard way to supply a custom query in Spring Data JPA?

    1. A. Annotate the method with @Query containing JPQL (or set nativeQuery=true to use raw SQL)Correct answer

      @Query declares JPQL directly on the repository method, and setting nativeQuery=true switches it to raw SQL — the standard way to supply a query that name derivation cannot express.

    2. B. Override the method body inside a @Configuration class

      Misplaces the query: repository queries are declared on the repository method itself, not implemented inside a @Configuration bean.

    3. C. Custom queries are not supported; you must fall back to JdbcTemplate

      False premise: custom queries are fully supported through @Query, so there is no need to abandon the repository for JdbcTemplate.

    4. D. Annotate the method with @Sql and inline the statement

      Misuses a test annotation: @Sql runs SQL scripts as test support and is unrelated to defining repository queries.

    Explanation

    When method-name derivation cannot express a query, Spring Data JPA lets you declare it directly on the repository method with the @Query annotation, written in JPQL by default or in raw SQL when nativeQuery is enabled. This keeps the custom query on the repository interface itself rather than requiring separate configuration or a different data-access API.

  4. Question 4

    Which derived repository method returns just the single most recent Order (the one with the greatest createdAt), using no @Query and no Pageable parameter?

    1. A. findByCreatedAtMax()

      Max is not a query-derivation keyword; there is no Max aggregate in derived method names.

    2. B. findAllByOrderByCreatedAtDesc()

      This returns every order sorted by createdAt descending, not a single row.

    3. C. findLatestByCreatedAt()

      Latest is not a recognized subject or keyword, so this name cannot be derived.

    4. D. findFirstByOrderByCreatedAtDesc()Correct answer

      First limits the result to one row and OrderByCreatedAtDesc sorts so the greatest createdAt comes first, yielding the most recent order.

    Explanation

    Combining the First limiting keyword with a static OrderBy...Desc clause returns exactly one row — the most recent — without a Pageable or a custom query. A Max aggregate and a Latest subject are not part of the derivation grammar, and the all-plus-orderby form returns the whole sorted list rather than a single result.

  5. Question 5

    In a Spring Data JPA repository interface you declare the method below and provide no implementation. What does Spring Data do with it? ```java public interface CustomerRepository extends JpaRepository<Customer, Long> { List<Customer> findByLastName(String lastName); } ```

    1. A. It throws at runtime because repository methods must be implemented by hand

      Assumes you must implement repository methods yourself, but you never do — Spring Data supplies the implementation for a valid property-based finder, so no runtime failure occurs.

    2. B. It parses the method name and derives the query automatically, supplying the implementation at runtimeCorrect answer

      Spring Data parses the method name (findBy + property), derives a JPQL query from it, and generates a proxy implementation at runtime — no code or @Query is needed for a property-based finder.

    3. C. It runs a native SQL stored procedure literally named findByLastName

      Confuses derivation with stored procedures: the generated query is derived JPQL, not a native SQL stored procedure literally named after the method.

    4. D. It fails at startup unless the method also carries a matching @Query annotation

      @Query is only required when name derivation is insufficient; a property-based finder like findByLastName is derived automatically and needs no @Query, so it does not fail at startup.

    Explanation

    Spring Data JPA's query-derivation mechanism parses a repository method name — the findBy prefix plus entity properties — and builds a JPQL query from it, then supplies a proxy implementation at runtime. For property-based finders this happens automatically, so neither a hand-written method body nor a @Query annotation is needed.

  6. Question 6

    A Spring Boot application declares `spring-boot-starter-data-jpa` and a single embedded H2 datasource, and defines JPA entity classes annotated with `@Entity`. The classes live in sub-packages beneath the package that holds the `@SpringBootApplication` class, and no `@EntityScan` annotation is present anywhere in the application. According to the Spring Boot reference documentation, how are those entity classes discovered?

    1. A. They are not discovered; without an explicit `@EntityScan` or a `persistence.xml` listing each class, Spring Boot cannot build a JPA persistence unit.

      Reflects the misconception that JPA in Spring Boot still requires a hand-maintained `persistence.xml` (or an explicit scan annotation). Spring Boot's auto-configuration deliberately removes that requirement — a `persistence.xml` is not needed and entity discovery happens automatically.

    2. B. Spring Boot scans automatically, starting from the package that contains the `@SpringBootApplication` (or `@EnableAutoConfiguration`) class and including its sub-packages.Correct answer

      Correct. The reference documentation states that classes annotated with `@Entity`, `@Embeddable`, or `@MappedSuperclass` are searched automatically, and by default all packages below the auto-configuration (main application) class are scanned — `@EntityScan` is only needed when entities live outside that root package.

    3. C. They are discovered only if each entity class is also registered as a Spring bean via `@Component` or an equivalent stereotype, since entity scanning reuses the component-scanning bean registry.

      Confuses entity scanning with component scanning. They are distinct mechanisms that happen to share a default root package: entities are located and registered with the `EntityManagerFactory` as managed persistent types, not instantiated as Spring beans, so no stereotype annotation is involved.

    4. D. They are discovered only if they sit in the same package as the `@Repository` interfaces that use them, because entity scanning is driven from each repository's declared domain type.

      Confuses repository scanning with entity scanning and invents a co-location rule. Entity discovery is package-scan based from the auto-configuration class and is entirely independent of where Spring Data repository interfaces are declared or what domain types they are parameterised with.

    Explanation

    Spring Boot's JPA auto-configuration removes the need to maintain a `persistence.xml`: it automatically searches for classes annotated with `@Entity`, `@Embeddable`, or `@MappedSuperclass`, and by default that search covers the package containing the auto-configuration (`@SpringBootApplication`/`@EnableAutoConfiguration`) class and everything beneath it, so entities in sub-packages are picked up with no extra annotation. `@EntityScan` exists only to redirect or widen that search when entities live outside the root package. Requiring a `persistence.xml` describes plain Java EE style bootstrapping rather than Boot's auto-configuration; requiring a stereotype annotation confuses entity scanning with component scanning, since entities are registered as persistent types with the `EntityManagerFactory` rather than as Spring beans; and tying discovery to repository packages confuses repository scanning with entity scanning, which is package-based and independent of any repository declaration.

  7. Question 7

    Which parameter do you add to a Spring Data query method to retrieve one page of results together with paging metadata?

    1. A. Two ints, offset and limit

      Incorrect: raw offset and limit ints are not how Spring Data expresses paging.

    2. B. A Sort argument only

      Incorrect: a Sort argument orders results but does not page them or return paging metadata.

    3. C. A Pageable argument, with the method returning Page<T>Correct answer

      Correct: a Pageable argument with the method returning Page<T> delivers the content plus total elements and pages.

    4. D. A @Limit annotation on the method

      Incorrect: there is no @Limit annotation used for paging query methods here.

    Explanation

    Passing a Pageable and returning Page<T> yields one page of content together with paging metadata such as total elements and pages. Sorting alone only orders results, and raw offset/limit integers or a limit annotation are not how Spring Data expresses paging.

  8. Question 8

    Code accesses a LAZY-fetched association after the persistence context has closed (outside any transaction). What is the typical result?

    1. A. A LazyInitializationException is thrownCorrect answer

      A LAZY association can only be initialized while its persistence context is open; touching it after the context closes throws LazyInitializationException.

    2. B. A NullPointerException is always thrown

      The uninitialized proxy is not null, so accessing it raises a lazy-initialization failure rather than a NullPointerException.

    3. C. The association is silently loaded with a fresh query

      Outside an open session there is no persistence context to issue a new query, so the association is not transparently re-loaded.

    4. D. Nothing happens and the collection is empty

      The association is not quietly resolved to an empty result; the failure surfaces as an exception rather than silently returning nothing.

    Explanation

    A LAZY association can only be initialized while its persistence context (Hibernate session) is still open; touching it after the context has closed raises a lazy-initialization failure rather than re-querying, returning empty data, or dereferencing null. Common remedies are a fetch-join query, eager fetching tailored to the use case, or keeping the transaction open across the access.

Practise all 17 Spring Data & JPA questions

Spring Certified Professional (Develop) has the full set, inside timed mock exams that mirror real exam conditions — every question with a worked explanation.

Open Spring Certified Professional (Develop)

Other topics in this pack