Spring Data JPA

Spring Data JPA similarly allows us to build repositories like Spring Data JDBC does, but internally it uses a much more powerful JPA-based implementation. Spring Data JPA has excellent support for both Hibernate and EclipseLink. On the fly, Spring Data JPA generates JPA queries based on the method name convention, providing an implementation for the Generic DAO pattern and adding support for the Querydsl library (http://www.querydsl.com), which enables elegant, type-safe, Java-based queries.

Now, let's create a straightforward application to demonstrate the basics of Spring Data JPA. The following dependency gets all the required modules for a Spring Boot application:

compile('org.springframework.boot:spring-boot-starter-data-jpa')

Spring Boot is smart enough to deduce that Spring Data JPA is being used, so it is not even required to add the @EnableJpaRepositories annotation (but we may do so if we wish). The Book entity should look as follows:

@Entity
@Table(name = "book")
public class Book {
   @Id
   private int id;
   private String title;

   // Constructors, getters, setters...
}

The Book entity marked with the javax.persistence.Entity annotation allows setting the entity name used in JPQL queries. The javax.persistence.Table annotation defines coordinates of the table and also may define constraints and indexes. It is important to note that instead of the org.springframework.data.annotation.Id annotation, we have to use the javax.persistence.Id annotation.

Now, let's define a CRUD repository with a custom method that uses a naming convention for query generation, as well as another method that uses a JPQL query:

@Repository
interface BookJpaRepository
   extends CrudRepository<Book, Integer> {

   Iterable<Book> findByIdBetween(int lower, int upper);

   @Query("SELECT b FROM Book b WHERE LENGTH(b.title) = " +
            "(SELECT MIN(LENGTH(b2.title)) FROM Book b2)")
   Iterable<Book> findShortestTitle();
}

A JDBC driver in the classpath, one Spring Boot dependency, the Book entity class, and the BookJpaRepository interface are enough to provide a basic but very versatile persistence layer based on the next stack of technologies—Spring Data JPA, JPA, JPQL, Hibernate, and JDBC.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.255.168