Spring Data JPA

The Spring Data Generated DAO – No More DAO Implementations

The DAO layer usually consists of a lot of boilerplate code that can and should be simplified. The advantages of such a simplification are many: a decrease in the number of artifacts that we need to define and maintain, consistency of data access patterns, and consistency of configuration.

Spring Data takes this simplification one step further 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.

In order to start leveraging the Spring Data programming model with JPA, a DAO interface needs to extend the JPA specific Repository interface, JpaRepository. This will enable Spring Data to find this interface and automatically create an implementation for it.

Automatic Custom Queries

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.

Let's look at an example. If the entity has a name field (and the Java Bean standard getName and setName methods), we'll define the findByName method in the DAO interface. This will automatically generate the correct query:

public interface IFooDAO extends JpaRepository<Foo, Long> {

    Foo findByName(String name);

}

Manual Custom Queries

Now let's look at a custom query that we'll define via the @Query annotation:

@Query("SELECT f FROM Foo f WHERE LOWER(f.name) = LOWER(:name)")

Foo retrieveByName(@Param("name") String name);


We can, of course, modify the auto-configuration by adding our customized explicit configuration.

Spring Boot provides an easy way to do this using properties in the application.properties file:

spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1

spring.datasource.username=sa

spring.datasource.password=sa

Repositories

1) JpaRepository - It extends PagingAndSortingRepository.

2) PagingAndSortingRepository - It extends CrudRepository.

3) CrudRepository - It extends Repository.


Question

Find the top 5 salary of employee

Answer. findTop5bySalaryOrderBySalarydesc




Comments

Popular posts from this blog

Java 8 : Find the number starts with 1 from a list of integers

Junit Mockito and Power Mockito

Important Linux Commands