Τρίτη 5 Οκτωβρίου 2021

Spring Certification: Spring Data JPA

What is a Spring Data Repository interface?
  • Spring Data Repositories are implementations of the DAO pattern
  • Spring Data provides: CrudRepository, JpaRepository, and PagingAndSortingRepository
  • We can extend these by defining our Entity: 
  • @Repository
    public interface DayActivityRepository extends JpaRepository<DayActivity, Long> {...}
  • And thus define the DAO pattern as an one-to-one relationship of an Entity with a Repository
  • In runtime, Spring's Data Access layer will implement automatically the above, using also the out-of-the-box EntityManager to perform crud operations.

How do you define a Spring Data Repository interface? Why is it an interface not a class?

  • Define a domain class-specific repository interface (e.g. DayActivityRepository) that extends Repository and is typed to the domain class (e.g. DayActivity) and an ID type. 
  • To expose CRUD methods for that domain type:  extend CrudRepository
  • To enable paging/sorting capabilities: extend PagingAndSortingRepository
  • To enable flushing the persistence context and deleting records in a batch: extend JpaRepository

  • It is an interface in order for Spring to create a JDK dynamic proxy for it, and fully implement it in runtime. Additionally, facilitates the use of generic parameter for our Entity. 


What is the naming convention for finder methods in a Spring Data Repository interface?
  • FIND | limit/top/distinct | BY | field(s) conditional expression | comparison | order expression
  • Example: findTop3ByNameOrSurnameContainsOrderByName ("searchTerm")


How are Spring Data repositories implemented by Spring at runtime?
  • Α JDK proxy (created from Spring's ProxyFactory API), and a QueryExecutorMethodInterceptor intercept all client calls to our @Repository, and then route usually to SimpleJpaRepository base class, which has implementations of defined methods
  • Additionally, @EnableJpaRepositories scans all @Repositories and creates Spring Beans, backed by default implementations of SimpleJpaRepository

What is @Query used for?
  • Define @Query on top of finder methods, in order to bypass call to these implementations, and act according to inner JPQL query

How to configure JPA with Spring Boot's Spring Data JPA ?
  • Pom dependencies:
    • spring-boot-starter (autoconfiguration)
    • spring-boot-starter-data-jpa (JPA Repositories hierarchy, hibernate core)
  • EntityManager factory:
    • Already provided with Hibernate as JPA provider
  • Datasource:
    • Auto-configured according to DB dependency in pom, and application properties (username, password, url, etc..)

Δεν υπάρχουν σχόλια:

Δημοσίευση σχολίου

What may be missing, or could get better?