# Spring Data JPA

* In entire web application, the DAO layer usually consists of a lot of boilerplate code that can be simplified.
* Benefits of simplification
  1. Decrease in the number of artifacts that we need to define and maintain.
  2. Consistency of data access patterns and consistency of configuration.
* Spring Data JPA framework takes this simplification one step forward and makes it possible to remove the DAO implementations entirely. The interface of the DAO is now the only artifact that we need to explicitly define.
* For this, a DAO interface needs to extend the JPA specific Repository interface `JpaRepository` or its super interface `CrudRepository`. This will enable Spring Data to find this interface and automatically create an implementation for it.
* By extending the interface we get the most required CRUD methods for standard data access available in a standard DAO.

## Crud Repository

* `org.springframework.data.repository.CrudRepository<T, ID>` methods are as follows,

```java
  long 	count() // Returns the number of entities available.
  void 	delete(T entity) // Deletes a given entity.
  void 	deleteAll() // Deletes all entities managed by the repository.
  void 	deleteAll(Iterable<? extends T> entities) // Deletes the given entities.
  void 	deleteById(ID id) // Deletes the entity with the given id.
  boolean 	existsById(ID id) // Returns whether an entity with the given id exists.
  Iterable<T> 	findAll() // Returns all instances of the type.
  Iterable<T> 	findAllById(Iterable<ID> ids) // Returns all instances of the type with the given IDs.
  Optional<T> 	findById(ID id) // Retrieves an entity by its id.
  <S extends T> S save(S entity) // Saves a given entity.
  <S extends T> Iterable<S> saveAll(Iterable<S> entities) // Saves all given entities.
```

## Jpa Repository

* `org.springframework.data.jpa.repository.JpaRepository<T, ID>`

```java
  void 	deleteAllInBatch() //Deletes all entities in a batch call.
  void 	deleteInBatch(Iterable<T> entities) // Deletes the given entities in a batch which means it will create a single Query.
  List<T> findAll() 
  <S extends T> List<S> findAll(Example<S> example) 
  <S extends T> List<S> findAll(Example<S> example, Sort sort) 
  List<T> findAll(Sort sort) 
  List<T> findAllById(Iterable<ID> ids) 
  void flush() // Flushes all pending changes to the database.
  T getOne(ID id) //Returns a reference to the entity with the given identifier.
  <S extends T> List<S> saveAll(Iterable<S> entities) 
```

## Custom Access Method and Queries

* By extending one of the Repository interfaces, the DAO will already have some basic `CRUD` methods *(and queries)* defined and implemented.
* To define more specific access methods, Spring JPA supports quite a few options:

1. When Spring Data creates a new Repository implementation, it analyses all the methods defined by the interfaces and tries to automatically generate queries from the method names. While this has some limitations, it’s a very powerful and elegant way of defining new custom access methods with very little effort.

* Consider following examples,
  * `findBy`, `And`, `Or`, `Distinct` example queries.

    ```java
      /* 
        select * from Customer c where c.name = name;
        -- gives only one customer
      */
      Customer findByName(String name);
      
      /*
        select * from Person p where p.emailAddress = emailAddress AND p.lastname = lastname
        -- returns multiple person, if more than one present
      */
      List<Person> findByEmailAddressAndLastname(EmailAddress emailAddress, String lastname);

      /*
        select DISTINCT(p) from Person p where p.lastname = lastname OR p.firstname = firstname
      */
      // Enables the distinct flag for the query
      List<Person> findDistinctPeopleByLastnameOrFirstname(String lastname, String firstname);
        
        // Enabling ignoring case for an individual property
      List<Person> findByLastnameIgnoreCase(String lastname);

        // Enabling static ORDER BY for a query
      List<Person> findByLastnameOrderByFirstnameAsc(String lastname);
      List<Person> findByAddressZipCode(ZipCode zipCode);
      // Assuming a Person has an Address with a ZipCode. In that case, the method creates the property traversal x.address.zipCode.

    ```
  * Limiting the result size of a query with Top and First.

    ```java
      // select * from User u order by u.lastname asc limit 1;
      User findFirstByOrderByLastnameAsc();
      // select * from User u order by u.lastname desc limit 10;
      User findTopByOrderByAgeDesc();

      Page<User> queryFirst10ByLastname(String lastname, Pageable pageable);

      Slice<User> findTop3ByLastname(String lastname, Pageable pageable);

      List<User> findFirst10ByLastname(String lastname, Sort sort);

      List<User> findTop10ByLastname(String lastname, Pageable pageable);
    ```

2. Simply define a new method in the interface and provide the actual `JPQL` query by using the `org.springframework.data.jpa.repository.@Query` annotation. This methods is used to write custom query.

```java

  @Query("select u from User u where u.emailAddress = :emailAddress")
  User findByEmailAddress(String emailAddress);

  @Query("SELECT p FROM Person p WHERE LOWER(p.name) = LOWER(:nm)")
  Foo retrieveByName(@Param("nm") String name);
```

* the `:` before arguments is use to specify named Parameters, which acts as place holder. Just like `?` in jdbc.
* `org.springframework.data.repository.query.@Param` is used to bind named parameters with query method param.&#x20;

## Transaction Configuration

* The actual implementation of the Spring Data managed DAO layer is hidden since we don’t work with it directly. `JpaRepository` interface through `JpaRepositoryImplementation` interface is implemented by the `org.springframework.data.jpa.repository.support.SimpleJpaRepository<T, ID>`, which defines default transaction mechanism using annotations.
  * The annotation used is `@Transacational` from `org.springframework.transaction.annotation`.
  * These tansaction can be easily overridden manually per method as well by supplying your own configurations.

## Exception Translation

* Exception translation is still enabled by the use of the `@Repository` annotation internally applied on the DAO implementation class.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://anon-coders-notes.gitbook.io/techwriterdev/languages/java/01_backend/09_springdatajpa/springdatajpa.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
