jpa : java persistence apibayoudhi-chaouki.e-monsite.com/medias/files/jpa-spring-data.pdf · jpa,...
TRANSCRIPT
![Page 1: JPA : Java Persistence APIbayoudhi-chaouki.e-monsite.com/medias/files/jpa-spring-data.pdf · JPA, the Java Persistence API, a specification for managing relational databases using](https://reader034.vdocuments.net/reader034/viewer/2022042600/5f4718e01cb50a1e014ff4c4/html5/thumbnails/1.jpg)
JPA : Java Persistence API
Chaouki Bayoudhi
![Page 2: JPA : Java Persistence APIbayoudhi-chaouki.e-monsite.com/medias/files/jpa-spring-data.pdf · JPA, the Java Persistence API, a specification for managing relational databases using](https://reader034.vdocuments.net/reader034/viewer/2022042600/5f4718e01cb50a1e014ff4c4/html5/thumbnails/2.jpg)
2
Introduction-->some background:
A resource server is a programmatic access point for your server’s functions and data (basically the same as an API server and/or possibly REST server).
JPA, the Java Persistence API, a specification for managing relational databases using Java. It describes an abstraction layer between Java classes and a relational database.
JPA is Java’s standard API specification for object-relational mapping.
Spring Data JPA is a wrapper around JPA providers such as Hibernate.
It makes persisting your Java classes as simple as adding some annotations and creating a simple repository interface.
No need to actually write persistence or retrieval methods.
Another great benefit is that you can change the underlying database implementation transparently without having to change any code. For example, in this tutorial, you’ll be using Postgres, but later if you decided you’d rather use MySQL, all you’d have to do is change out some dependencies.
![Page 3: JPA : Java Persistence APIbayoudhi-chaouki.e-monsite.com/medias/files/jpa-spring-data.pdf · JPA, the Java Persistence API, a specification for managing relational databases using](https://reader034.vdocuments.net/reader034/viewer/2022042600/5f4718e01cb50a1e014ff4c4/html5/thumbnails/3.jpg)
3
Spring Data : Definition
Spring Data is a module of Spring Framework. The goal of Spring Data repository abstraction is to significantly reduce the amount of boilerplate code required to implement data access layers for various persistence stores.
Spring Data JPA is a part of Spring Data and it supports Hibernate 5, OpenJPA 2.4, and EclipseLink 2.6.1.
Spring Data JPA is not a JPA provider.
It is a library/framework that adds an extra layer of abstraction on the top of our JPA provider (like Hibernate). If we decide to use Spring Data JPA, the repository layer of our application contains three layers.
![Page 4: JPA : Java Persistence APIbayoudhi-chaouki.e-monsite.com/medias/files/jpa-spring-data.pdf · JPA, the Java Persistence API, a specification for managing relational databases using](https://reader034.vdocuments.net/reader034/viewer/2022042600/5f4718e01cb50a1e014ff4c4/html5/thumbnails/4.jpg)
4
Spring Data : Definition
![Page 5: JPA : Java Persistence APIbayoudhi-chaouki.e-monsite.com/medias/files/jpa-spring-data.pdf · JPA, the Java Persistence API, a specification for managing relational databases using](https://reader034.vdocuments.net/reader034/viewer/2022042600/5f4718e01cb50a1e014ff4c4/html5/thumbnails/5.jpg)
5
Spring Data : Definition
1- Spring Data JPA provides support for creating JPA repositories by extending the Spring Data repository interfaces.
2- Spring Data Commons provides the infrastructure that is shared by the datastore-specific Spring Data projects.
3- The JPA Provider (like hibernate) implements the Java Persistence API.
![Page 6: JPA : Java Persistence APIbayoudhi-chaouki.e-monsite.com/medias/files/jpa-spring-data.pdf · JPA, the Java Persistence API, a specification for managing relational databases using](https://reader034.vdocuments.net/reader034/viewer/2022042600/5f4718e01cb50a1e014ff4c4/html5/thumbnails/6.jpg)
6
API Mapping of Spring Data JPA and JPA
The SimpleJpaRepository class provides the default implementation of a Repository interface. SimpleJpaRepository class internally uses JPA EntityManager to map its methods with JPA EntityManager interface methods.
It is better to know which JPA EntityManager method is being called by methods of Repository interface (SimpleJpaRepository class ) of Spring Data JPA.
The JPA methods called by main methods of Repository interface of Spring Data JPA are shown below.
![Page 7: JPA : Java Persistence APIbayoudhi-chaouki.e-monsite.com/medias/files/jpa-spring-data.pdf · JPA, the Java Persistence API, a specification for managing relational databases using](https://reader034.vdocuments.net/reader034/viewer/2022042600/5f4718e01cb50a1e014ff4c4/html5/thumbnails/7.jpg)
7
API Mapping of Spring Data JPA and JPA
![Page 8: JPA : Java Persistence APIbayoudhi-chaouki.e-monsite.com/medias/files/jpa-spring-data.pdf · JPA, the Java Persistence API, a specification for managing relational databases using](https://reader034.vdocuments.net/reader034/viewer/2022042600/5f4718e01cb50a1e014ff4c4/html5/thumbnails/8.jpg)
8
The basic flow at the time of accessing the database using Spring Data JPA
![Page 9: JPA : Java Persistence APIbayoudhi-chaouki.e-monsite.com/medias/files/jpa-spring-data.pdf · JPA, the Java Persistence API, a specification for managing relational databases using](https://reader034.vdocuments.net/reader034/viewer/2022042600/5f4718e01cb50a1e014ff4c4/html5/thumbnails/9.jpg)
9
Spring Data JPA Features
Sophisticated support to build repositories based on Spring and JPA.
Support for QueryDsl predicates and thus type-safe JPA queries.
Transparent auditing of a domain class.
Pagination support, dynamic query execution, the ability to integrate custom data access code.
Validation of @Query annotated queries at a bootstrap time.
Support for XML based entity mapping.
JavaConfig based repository configuration by introducing @EnableJpaRepositories.
![Page 10: JPA : Java Persistence APIbayoudhi-chaouki.e-monsite.com/medias/files/jpa-spring-data.pdf · JPA, the Java Persistence API, a specification for managing relational databases using](https://reader034.vdocuments.net/reader034/viewer/2022042600/5f4718e01cb50a1e014ff4c4/html5/thumbnails/10.jpg)
10
Spring Data Commons and Spring Data JPA Repositories/interfaces
The diagram below shows the main interfaces from Spring Data Commons and Spring Data JPA modules.
![Page 11: JPA : Java Persistence APIbayoudhi-chaouki.e-monsite.com/medias/files/jpa-spring-data.pdf · JPA, the Java Persistence API, a specification for managing relational databases using](https://reader034.vdocuments.net/reader034/viewer/2022042600/5f4718e01cb50a1e014ff4c4/html5/thumbnails/11.jpg)
11
Spring Data Commons and Spring Data JPA Repositories/interfaces
![Page 12: JPA : Java Persistence APIbayoudhi-chaouki.e-monsite.com/medias/files/jpa-spring-data.pdf · JPA, the Java Persistence API, a specification for managing relational databases using](https://reader034.vdocuments.net/reader034/viewer/2022042600/5f4718e01cb50a1e014ff4c4/html5/thumbnails/12.jpg)
12
Spring Data Commons
Spring Data Commons is part of the umbrella Spring Data project that provides shared infrastructure across the Spring Data projects.
It contains technology neutral repository interfaces as well as a metadata model for persisting Java classes.
Spring Data Commons project provides the following interfaces:
![Page 13: JPA : Java Persistence APIbayoudhi-chaouki.e-monsite.com/medias/files/jpa-spring-data.pdf · JPA, the Java Persistence API, a specification for managing relational databases using](https://reader034.vdocuments.net/reader034/viewer/2022042600/5f4718e01cb50a1e014ff4c4/html5/thumbnails/13.jpg)
13
Spring Data Commons
1- Repository<T, ID extends Serializable> interface
2- CrudRepository<T, ID extends Serializable> interface
3- PagingAndSortingRepository<T, ID extends Serializable> interface
4- QueryDslPredicateExecutor interface
![Page 14: JPA : Java Persistence APIbayoudhi-chaouki.e-monsite.com/medias/files/jpa-spring-data.pdf · JPA, the Java Persistence API, a specification for managing relational databases using](https://reader034.vdocuments.net/reader034/viewer/2022042600/5f4718e01cb50a1e014ff4c4/html5/thumbnails/14.jpg)
14
The Repository<T, ID extends Serializable> interface
The Repository<T, ID extends Serializable> interface is a marker interface that has two purposes :
1- It captures the type of the managed entity and the type of the entity’s id.
2- It helps the Spring container to discover the “concrete” repository interfaces during classpath scanning.
![Page 15: JPA : Java Persistence APIbayoudhi-chaouki.e-monsite.com/medias/files/jpa-spring-data.pdf · JPA, the Java Persistence API, a specification for managing relational databases using](https://reader034.vdocuments.net/reader034/viewer/2022042600/5f4718e01cb50a1e014ff4c4/html5/thumbnails/15.jpg)
15
The Repository<T, ID> Source Code
package org.springframework.data.repository;
import org.springframework.stereotype.Indexed;
@Indexed //indicate that this interface represents a //stereotype for the index (uses a metadata file //generated at the compilation time)
public interface Repository<T, ID> {
}
![Page 16: JPA : Java Persistence APIbayoudhi-chaouki.e-monsite.com/medias/files/jpa-spring-data.pdf · JPA, the Java Persistence API, a specification for managing relational databases using](https://reader034.vdocuments.net/reader034/viewer/2022042600/5f4718e01cb50a1e014ff4c4/html5/thumbnails/16.jpg)
16
The CrudRepository<T, ID extends Serializable> interface
The CrudRepository<T, ID extends Serializable> interface provides CRUD (Create, Read, Update, Delete) operations for the managed entity.
Source Code :
package org.springframework.data.repository;
import java.util.Optional;
@NoRepositoryBean //avoid creating repository proxies for this interface
public interface CrudRepository < T, ID > extends Repository < T, ID > {
<S extends T > S save(S entity);
<S extends T > Iterable < S > saveAll(Iterable < S > entities);
Optional < T > findById(ID id);
![Page 17: JPA : Java Persistence APIbayoudhi-chaouki.e-monsite.com/medias/files/jpa-spring-data.pdf · JPA, the Java Persistence API, a specification for managing relational databases using](https://reader034.vdocuments.net/reader034/viewer/2022042600/5f4718e01cb50a1e014ff4c4/html5/thumbnails/17.jpg)
17
The CrudRepository<T, ID> methods/APIs
boolean existsById(ID id);
Iterable < T > findAll();
Iterable < T > findAllById(Iterable < ID > ids);
long count();
void deleteById(ID id);
void delete(T entity);
void deleteAll();
}
![Page 18: JPA : Java Persistence APIbayoudhi-chaouki.e-monsite.com/medias/files/jpa-spring-data.pdf · JPA, the Java Persistence API, a specification for managing relational databases using](https://reader034.vdocuments.net/reader034/viewer/2022042600/5f4718e01cb50a1e014ff4c4/html5/thumbnails/18.jpg)
18
The CrudRepository<T, ID extends Serializable> interface
The usage of each method :
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.
![Page 19: JPA : Java Persistence APIbayoudhi-chaouki.e-monsite.com/medias/files/jpa-spring-data.pdf · JPA, the Java Persistence API, a specification for managing relational databases using](https://reader034.vdocuments.net/reader034/viewer/2022042600/5f4718e01cb50a1e014ff4c4/html5/thumbnails/19.jpg)
19
The CrudRepository<T, ID extends Serializable> interface
Iterable findAll() - Returns all instances of the type.
Iterable findAllById(Iterable ids) - Returns all instances of the type with the given IDs.
Optional findById(ID id) - Retrieves an entity by its id.
save(S entity) - Saves a given entity.
Iterable saveAll(Iterable entities) - Saves all given entities.
![Page 20: JPA : Java Persistence APIbayoudhi-chaouki.e-monsite.com/medias/files/jpa-spring-data.pdf · JPA, the Java Persistence API, a specification for managing relational databases using](https://reader034.vdocuments.net/reader034/viewer/2022042600/5f4718e01cb50a1e014ff4c4/html5/thumbnails/20.jpg)
20
The PagingAndSortingRepository<T, ID extends Serializable> interface
The PagingAndSortingRepository<T, ID extends Serializable> interface is an extension of CrudRepository to provide additional methods to retrieve entities using the pagination and sorting abstraction.
Pagination is often helpful when we have a large dataset and we want to present it to the user in smaller chunks.
We often need to sort that data by some criteria while paging.
![Page 21: JPA : Java Persistence APIbayoudhi-chaouki.e-monsite.com/medias/files/jpa-spring-data.pdf · JPA, the Java Persistence API, a specification for managing relational databases using](https://reader034.vdocuments.net/reader034/viewer/2022042600/5f4718e01cb50a1e014ff4c4/html5/thumbnails/21.jpg)
21
The PagingAndSortingRepository<T, ID> Methods/APIs
package org.springframework.data.repository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
@NoRepositoryBean
public interface PagingAndSortingRepository < T, ID > extends CrudRepository < T, ID > {
/**
* Returns all entities sorted by the given options.
*
* @param sort
* @return all entities sorted by the given options
*/
Iterable < T > findAll(Sort sort);
![Page 22: JPA : Java Persistence APIbayoudhi-chaouki.e-monsite.com/medias/files/jpa-spring-data.pdf · JPA, the Java Persistence API, a specification for managing relational databases using](https://reader034.vdocuments.net/reader034/viewer/2022042600/5f4718e01cb50a1e014ff4c4/html5/thumbnails/22.jpg)
22
/**
* Returns a {@link Page} of entities meeting the paging restriction provided in the {@code Pageable} object.
*
* @param pageable
* @return a page of entities
*/
Page < T > findAll(Pageable pageable);
}
![Page 23: JPA : Java Persistence APIbayoudhi-chaouki.e-monsite.com/medias/files/jpa-spring-data.pdf · JPA, the Java Persistence API, a specification for managing relational databases using](https://reader034.vdocuments.net/reader034/viewer/2022042600/5f4718e01cb50a1e014ff4c4/html5/thumbnails/23.jpg)
23
The QueryDslPredicateExecutor interface
The QueryDslPredicateExecutor interface is not a “repository interface”.
It declares the methods that are used to retrieve entities from the database by using QueryDsl Predicate objects.
Source Code :
package org.springframework.data.querydsl;
import java.util.Optional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import com.querydsl.core.types.OrderSpecifier;
import com.querydsl.core.types.Predicate;
public interface QuerydslPredicateExecutor < T > {
![Page 24: JPA : Java Persistence APIbayoudhi-chaouki.e-monsite.com/medias/files/jpa-spring-data.pdf · JPA, the Java Persistence API, a specification for managing relational databases using](https://reader034.vdocuments.net/reader034/viewer/2022042600/5f4718e01cb50a1e014ff4c4/html5/thumbnails/24.jpg)
24
The QueryDslPredicateExecutor methods/APIs
Optional < T > findOne(Predicate predicate);
Iterable < T > findAll(Predicate predicate);
Iterable < T > findAll(Predicate predicate, Sort sort);
Iterable < T > findAll(Predicate predicate, OrderSpecifier << ? > ...orders);
Iterable < T > findAll(OrderSpecifier << ? > ...orders);
Page < T > findAll(Predicate predicate, Pageable pageable);
long count(Predicate predicate);
boolean exists(Predicate predicate);
}
![Page 25: JPA : Java Persistence APIbayoudhi-chaouki.e-monsite.com/medias/files/jpa-spring-data.pdf · JPA, the Java Persistence API, a specification for managing relational databases using](https://reader034.vdocuments.net/reader034/viewer/2022042600/5f4718e01cb50a1e014ff4c4/html5/thumbnails/25.jpg)
25
Spring Data JPA Interfaces
Spring Data JPA module deals with enhanced support for JPA based data access layers.
Spring Data JPA project provides the following interfaces:
1- JpaRepository<T, ID extends Serializable> interface.
2- JpaSpecificationExecutor interface.
![Page 26: JPA : Java Persistence APIbayoudhi-chaouki.e-monsite.com/medias/files/jpa-spring-data.pdf · JPA, the Java Persistence API, a specification for managing relational databases using](https://reader034.vdocuments.net/reader034/viewer/2022042600/5f4718e01cb50a1e014ff4c4/html5/thumbnails/26.jpg)
26
JpaRepository<T, ID extends Serializable> interface
The JpaRepository<T, ID extends Serializable> interface is a JPA specific repository interface that combines the methods declared by the common repository interfaces behind a single interface.
Source Code :
package org.springframework.data.jpa.repository;
import java.util.List;
import javax.persistence.EntityManager;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Sort;
import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.QueryByExampleExecutor;
@NoRepositoryBean
public interface JpaRepository < T, ID > extends PagingAndSortingRepository < T, ID > , QueryByExampleExecutor < T > {
![Page 27: JPA : Java Persistence APIbayoudhi-chaouki.e-monsite.com/medias/files/jpa-spring-data.pdf · JPA, the Java Persistence API, a specification for managing relational databases using](https://reader034.vdocuments.net/reader034/viewer/2022042600/5f4718e01cb50a1e014ff4c4/html5/thumbnails/27.jpg)
27
JpaRepository<T, ID> methods/APIs
List < T > findAll();
List < T > findAll(Sort sort);
List < T > findAllById(Iterable < ID > ids);
<S extends T > List < S > saveAll(Iterable < S > entities);
void flush();
<S extends T > S saveAndFlush(S entity);
void deleteInBatch(Iterable < T > entities);
void deleteAllInBatch();
T getOne(ID id);
@Override <S extends T > List < S > findAll(Example < S > example);
@Override <S extends T > List < S > findAll(Example < S > example, Sort sort);}
![Page 28: JPA : Java Persistence APIbayoudhi-chaouki.e-monsite.com/medias/files/jpa-spring-data.pdf · JPA, the Java Persistence API, a specification for managing relational databases using](https://reader034.vdocuments.net/reader034/viewer/2022042600/5f4718e01cb50a1e014ff4c4/html5/thumbnails/28.jpg)
28
JpaSpecificationExecutor interface
The JpaSpecificationExecutor interface is not a “repository interface”.
It declares the methods that are used to retrieve entities from the database by using Specification objects that use the JPA criteria API.
![Page 29: JPA : Java Persistence APIbayoudhi-chaouki.e-monsite.com/medias/files/jpa-spring-data.pdf · JPA, the Java Persistence API, a specification for managing relational databases using](https://reader034.vdocuments.net/reader034/viewer/2022042600/5f4718e01cb50a1e014ff4c4/html5/thumbnails/29.jpg)
29
JpaSpecificationExecutor methods/APIspackage org.springframework.data.jpa.repository;
import java.util.List;
import java.util.Optional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.lang.Nullable;
public interface JpaSpecificationExecutor<T> {
Optional<T> findOne(@Nullable Specification<T> spec);
List<T> findAll(@Nullable Specification<T> spec);
Page<T> findAll(@Nullable Specification<T> spec, Pageable pageable);
List<T> findAll(@Nullable Specification<T> spec, Sort sort);
long count(@Nullable Specification<T> spec);
}
![Page 30: JPA : Java Persistence APIbayoudhi-chaouki.e-monsite.com/medias/files/jpa-spring-data.pdf · JPA, the Java Persistence API, a specification for managing relational databases using](https://reader034.vdocuments.net/reader034/viewer/2022042600/5f4718e01cb50a1e014ff4c4/html5/thumbnails/30.jpg)
30
How to Use Spring Data JPA interfaces
we have seen what is Spring Data JPA and it's main interfaces.
Now the question is how to use them?
Four steps to use Spring Data JPA repositories/interfaces.
1- Create a repository interface and extend one of the repository interfaces provided by Spring Data :
public interface ToyRepository extends CrudRepository<Toy, Long> {
}
![Page 31: JPA : Java Persistence APIbayoudhi-chaouki.e-monsite.com/medias/files/jpa-spring-data.pdf · JPA, the Java Persistence API, a specification for managing relational databases using](https://reader034.vdocuments.net/reader034/viewer/2022042600/5f4718e01cb50a1e014ff4c4/html5/thumbnails/31.jpg)
31
How to Use Spring Data JPA interfaces
2- Add custom query methods to the created repository interface (if we need them that is).
public interface CustomerRepository extends CrudRepository<Toy, Long> {
long deleteByName(String name);
List<Toy> removeByName(String name);
long countByNameame(String name);
}
}
![Page 32: JPA : Java Persistence APIbayoudhi-chaouki.e-monsite.com/medias/files/jpa-spring-data.pdf · JPA, the Java Persistence API, a specification for managing relational databases using](https://reader034.vdocuments.net/reader034/viewer/2022042600/5f4718e01cb50a1e014ff4c4/html5/thumbnails/32.jpg)
32
How to Use Spring Data JPA interfaces
3- Set up Spring to create proxy instances for those interfaces, either with JavaConfig or with XML configuration.
To use Java configuration, create a class similar to the following:
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@EnableJpaRepositories
public class Config {}
![Page 33: JPA : Java Persistence APIbayoudhi-chaouki.e-monsite.com/medias/files/jpa-spring-data.pdf · JPA, the Java Persistence API, a specification for managing relational databases using](https://reader034.vdocuments.net/reader034/viewer/2022042600/5f4718e01cb50a1e014ff4c4/html5/thumbnails/33.jpg)
33
How to Use Spring Data JPA interfaces
To use XML configuration, define a bean similar to the following:
![Page 34: JPA : Java Persistence APIbayoudhi-chaouki.e-monsite.com/medias/files/jpa-spring-data.pdf · JPA, the Java Persistence API, a specification for managing relational databases using](https://reader034.vdocuments.net/reader034/viewer/2022042600/5f4718e01cb50a1e014ff4c4/html5/thumbnails/34.jpg)
34
How to Use Spring Data JPA interfaces
To use XML configuration, define a bean similar to the following:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<jpa:repositories base-package="com.acme.repositories"/>
</beans>
![Page 35: JPA : Java Persistence APIbayoudhi-chaouki.e-monsite.com/medias/files/jpa-spring-data.pdf · JPA, the Java Persistence API, a specification for managing relational databases using](https://reader034.vdocuments.net/reader034/viewer/2022042600/5f4718e01cb50a1e014ff4c4/html5/thumbnails/35.jpg)
35
How to Use Spring Data JPA interfaces
4- Inject the repository interface to another component and use the implementation that is provided automatically by Spring.
@Service
public class ToyServiceImpl implements ToyService {
@Autowired
private ToyRepository toyRepository;
@Override
@Transactional
public List < Toy > getToys() {
return toyRepository.findAll();
}
@Override
@Transactional
public void saveToy(Toy theToy) {
toyRepository.save(theToy);
}
![Page 36: JPA : Java Persistence APIbayoudhi-chaouki.e-monsite.com/medias/files/jpa-spring-data.pdf · JPA, the Java Persistence API, a specification for managing relational databases using](https://reader034.vdocuments.net/reader034/viewer/2022042600/5f4718e01cb50a1e014ff4c4/html5/thumbnails/36.jpg)
36
How to Use Spring Data JPA interfaces
@Override
@Transactional
public Toy getToy(int id) throws ResourceNotFoundException {
return toyRepository.findById(id).orElseThrow(
() - > new ResourceNotFoundException(id));
}
@Override
@Transactional
public void deleteToy(int theId) {
toyRepository.deleteById(theId);
}
}
![Page 37: JPA : Java Persistence APIbayoudhi-chaouki.e-monsite.com/medias/files/jpa-spring-data.pdf · JPA, the Java Persistence API, a specification for managing relational databases using](https://reader034.vdocuments.net/reader034/viewer/2022042600/5f4718e01cb50a1e014ff4c4/html5/thumbnails/37.jpg)
37
Summary
Spring Data JPA is not a JPA provider. It simply “hides” the Java Persistence API (and the JPA provider) behind its repository abstraction.
We have seen multiple repository interfaces that Spring Data provides and that are used for different purposes.
We have discussed briefly how to use these Spring data interfaces with sample code examples.
![Page 38: JPA : Java Persistence APIbayoudhi-chaouki.e-monsite.com/medias/files/jpa-spring-data.pdf · JPA, the Java Persistence API, a specification for managing relational databases using](https://reader034.vdocuments.net/reader034/viewer/2022042600/5f4718e01cb50a1e014ff4c4/html5/thumbnails/38.jpg)
38
Examples
![Page 39: JPA : Java Persistence APIbayoudhi-chaouki.e-monsite.com/medias/files/jpa-spring-data.pdf · JPA, the Java Persistence API, a specification for managing relational databases using](https://reader034.vdocuments.net/reader034/viewer/2022042600/5f4718e01cb50a1e014ff4c4/html5/thumbnails/39.jpg)
39
Example1
Spring Data JPA offers various ways to create a query. In this first example, we will focus on how to generate a query using method name strategy.
The following simple example shows what a JPA query method translates into:
![Page 40: JPA : Java Persistence APIbayoudhi-chaouki.e-monsite.com/medias/files/jpa-spring-data.pdf · JPA, the Java Persistence API, a specification for managing relational databases using](https://reader034.vdocuments.net/reader034/viewer/2022042600/5f4718e01cb50a1e014ff4c4/html5/thumbnails/40.jpg)
40
Example1
public interface ToyRepository extends Repository<Toy, Long> {
List<Toy> findByEmailAddressAndLastname(String emailAddress, String type);
}
Spring Data JPA creates a query using the JPA criteria API from this, but, essentially, this translates into the following query: select u from Toy u where u.emailAddress = ?1 and u.type = ?2.
![Page 41: JPA : Java Persistence APIbayoudhi-chaouki.e-monsite.com/medias/files/jpa-spring-data.pdf · JPA, the Java Persistence API, a specification for managing relational databases using](https://reader034.vdocuments.net/reader034/viewer/2022042600/5f4718e01cb50a1e014ff4c4/html5/thumbnails/41.jpg)
41
Example1
Let's create an example to demonstrate the usage of above all keywords. Before creating ToyRepository, let's create Toy JPA entity on which we will perform database operations.
![Page 42: JPA : Java Persistence APIbayoudhi-chaouki.e-monsite.com/medias/files/jpa-spring-data.pdf · JPA, the Java Persistence API, a specification for managing relational databases using](https://reader034.vdocuments.net/reader034/viewer/2022042600/5f4718e01cb50a1e014ff4c4/html5/thumbnails/42.jpg)
42
Example1 : JPA Entity - Toy.javaimport java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "toys")
public class Toy {
@Id @GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
private String type;
private double price;
//you can put annotations on getters ou on fields//@Id //@GeneratedValue(strategy = GenerationType.AUTO) public long getId() { return id; }
public void setId(long id) { this.id = id; }//other setters and getters}//End Class Toy
![Page 43: JPA : Java Persistence APIbayoudhi-chaouki.e-monsite.com/medias/files/jpa-spring-data.pdf · JPA, the Java Persistence API, a specification for managing relational databases using](https://reader034.vdocuments.net/reader034/viewer/2022042600/5f4718e01cb50a1e014ff4c4/html5/thumbnails/43.jpg)
43
Example1 : Spring Data JPA Repository - ToyRepository.javaimport java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
Import com.jee.tp.ServerToy.Toy;
/**
* ToyRepository demonstrates the method name query generation.
* @author Chaouki Bayoudhi
*
*/
@Repository
public interface ToyRepository extends JpaRepository<Toy, Long> {
Optional<Toy> findByNameAndType(String name, String type);
Optional<Toy> findByNameOrType(String name, String type);
List<Toy> findByPriceBetween(double price1, double price2);
List<Toy> findByPriceLessThan(double price);
List<Toy> findByPriceGreaterThan(double price);
![Page 44: JPA : Java Persistence APIbayoudhi-chaouki.e-monsite.com/medias/files/jpa-spring-data.pdf · JPA, the Java Persistence API, a specification for managing relational databases using](https://reader034.vdocuments.net/reader034/viewer/2022042600/5f4718e01cb50a1e014ff4c4/html5/thumbnails/44.jpg)
44
Example1 : Spring Data JPA Repository - ToyRepository.java
List<Toy> findByNameLike(String name);
List<Toy> findByNameNotLike(String name);
Optional<Toy> findByNameStartingWith(String name);
Optional<Toy> findByPriceOrderByNameameDesc(double price);
List<Toy> findByTypeNot(String type);
List<Toy> findByPriceIn(Collection<Double> prices);
List<Toy> findByPriceNotIn(Collection<Double> prices);
List<Toy> findByNameIgnoreCase(String name);
}
![Page 45: JPA : Java Persistence APIbayoudhi-chaouki.e-monsite.com/medias/files/jpa-spring-data.pdf · JPA, the Java Persistence API, a specification for managing relational databases using](https://reader034.vdocuments.net/reader034/viewer/2022042600/5f4718e01cb50a1e014ff4c4/html5/thumbnails/45.jpg)
45
Rules for Creating Query Methods
The query generation from the method name is a query generation strategy where the invoked query is derived from the name of the query method.
We can create query methods that use this strategy by following these rules:
The name of our query method must start with one of the following prefixes: find…By, read…By, query…By, count…By, and get…By.
If we want to limit the number of returned query results, we can add the First or the Top keyword before the first By word. If we want to get more than one result, we have to append the optional numeric value to the First and the Top keywords. For example, findTopBy, findTop1By, findFirstBy, and findFirst1By all return the first entity that matches the specified search criteria.
If we want to select unique results, we have to add the Distinct keyword before the first By word. For example, findTitleDistinctBy or findDistinctTitleBy means that we want to select all unique titles that are found from the database.
![Page 46: JPA : Java Persistence APIbayoudhi-chaouki.e-monsite.com/medias/files/jpa-spring-data.pdf · JPA, the Java Persistence API, a specification for managing relational databases using](https://reader034.vdocuments.net/reader034/viewer/2022042600/5f4718e01cb50a1e014ff4c4/html5/thumbnails/46.jpg)
46
Rules for Creating Query Methods
you must add the search criteria of our query method after the first By word.
You can specify the search criteria by combining property expressions with the supported keywords.
If our query method specifies x search conditions, you must add x method parameters to it. In other words, the number of method parameters must be equal than the number of search conditions. Also, the method parameters must be given in the same order than the search conditions.
you must set the return type of the query method by following the rules that were described in the previous part of this tutorial.
![Page 47: JPA : Java Persistence APIbayoudhi-chaouki.e-monsite.com/medias/files/jpa-spring-data.pdf · JPA, the Java Persistence API, a specification for managing relational databases using](https://reader034.vdocuments.net/reader034/viewer/2022042600/5f4718e01cb50a1e014ff4c4/html5/thumbnails/47.jpg)
47
Example 2
![Page 48: JPA : Java Persistence APIbayoudhi-chaouki.e-monsite.com/medias/files/jpa-spring-data.pdf · JPA, the Java Persistence API, a specification for managing relational databases using](https://reader034.vdocuments.net/reader034/viewer/2022042600/5f4718e01cb50a1e014ff4c4/html5/thumbnails/48.jpg)
48
Example 2import java.time.ZonedDateTime;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Version;
import org.hibernate.annotations.Type;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
@Entity
@Table(name = "todos")
public class Todo {
static final int MAX_LENGTH_DESCRIPTION = 500;
static final int MAX_LENGTH_TITLE = 100;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "created_by_user", nullable = false)
@CreatedBy
private String createdByToy;
@Column(name = "creation_time", nullable = false)
@Type(type = "org.jadira.usertype.dateandtime.threeten.PersistentZonedDateTime")
@CreatedDate
private ZonedDateTime creationTime;
![Page 49: JPA : Java Persistence APIbayoudhi-chaouki.e-monsite.com/medias/files/jpa-spring-data.pdf · JPA, the Java Persistence API, a specification for managing relational databases using](https://reader034.vdocuments.net/reader034/viewer/2022042600/5f4718e01cb50a1e014ff4c4/html5/thumbnails/49.jpg)
49
Example 2
@Column(name = "description", length = MAX_LENGTH_DESCRIPTION)
private String description;
@Column(name = "modified_by_user", nullable = false)
@LastModifiedBy
private String modifiedByToy;
@Column(name = "modification_time")
@Type(type = "org.jadira.usertype.dateandtime.threeten.PersistentZonedDateTime")
@LastModifiedDate
private ZonedDateTime modificationTime;
@Column(name = "title", nullable = false, length = MAX_LENGTH_TITLE)
private String title;
@Version
private long version;
![Page 50: JPA : Java Persistence APIbayoudhi-chaouki.e-monsite.com/medias/files/jpa-spring-data.pdf · JPA, the Java Persistence API, a specification for managing relational databases using](https://reader034.vdocuments.net/reader034/viewer/2022042600/5f4718e01cb50a1e014ff4c4/html5/thumbnails/50.jpg)
50
Example 2
/**
* This entity is so simple that you don't really need to use the builder pattern
* (use a constructor instead). I use the builder pattern here because it makes
* the code a bit more easier to read.
*/
static class Builder {
private String description;
private String title;
private Builder() {}
Builder description(String description) {
this.description = description;
return this;
}
Builder title(String title) {
this.title = title;
return this;
}
Todo build() {
Todo build = new Todo(this);
return build;
}
}
}
![Page 51: JPA : Java Persistence APIbayoudhi-chaouki.e-monsite.com/medias/files/jpa-spring-data.pdf · JPA, the Java Persistence API, a specification for managing relational databases using](https://reader034.vdocuments.net/reader034/viewer/2022042600/5f4718e01cb50a1e014ff4c4/html5/thumbnails/51.jpg)
51
Example 2 : Spring Data JPA - TodoRepository.java
Refer below source code examples gives you more idea about how to create database queries using method names.
![Page 52: JPA : Java Persistence APIbayoudhi-chaouki.e-monsite.com/medias/files/jpa-spring-data.pdf · JPA, the Java Persistence API, a specification for managing relational databases using](https://reader034.vdocuments.net/reader034/viewer/2022042600/5f4718e01cb50a1e014ff4c4/html5/thumbnails/52.jpg)
52
Example 2 : Spring Data JPA - TodoRepository.java
import java.util.List;
import java.util.Optional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.Repository;
import org.springframework.data.repository.query.Param;
import net.guides.springboot2.springboottestingexamples.model.Todo;
/**
* This repository provides CRUD operations for {@link net.petrikainulainen.springdata.jpa.todo.Todo}
* objects.
*
*/
interface TodoRepository extends Repository < Todo, Long > {
void delete(Todo deleted);
List < Todo > findAll();
/**
* This query method creates the invoked query method by parsing it from the method name of the query method.
* @param descriptionPart The part that must be found from the description of the todo entry.
* @param titlePart The part that must be found from the title of the todo entry.
* @param pageRequest The information of the requested page.
* @return A page of todo entries whose title or description contains with the given search term. The content of
* the returned page depends from the page request given as a method parameter.
*/
Page < Todo > findByDescriptionContainsOrTitleContainsAllIgnoreCase(String descriptionPart,
String titlePart,
Pageable pageRequest);
/**
* This query method creates the invoked query method by parsing it from the method name of the query method.
* @param descriptionPart The part that must be found from the description of the todo entry.
* @param titlePart The part that must be found from the title of the todo entry.
* @return A list of todo entries whose title or description contains with the given search criteria. The returned
* todo entries are sorted in alphabetical order by using the title of the todo entry.
*/
List < Todo > findByDescriptionContainsOrTitleContainsAllIgnoreCaseOrderByTitleAsc(String descriptionPart,
String titlePart);
![Page 53: JPA : Java Persistence APIbayoudhi-chaouki.e-monsite.com/medias/files/jpa-spring-data.pdf · JPA, the Java Persistence API, a specification for managing relational databases using](https://reader034.vdocuments.net/reader034/viewer/2022042600/5f4718e01cb50a1e014ff4c4/html5/thumbnails/53.jpg)
53
Example 2 : Spring Data JPA - TodoRepository.java
/**
* This query method invokes the named JPQL query that is configured in the {@code Todo} class by using the
* {@code @NamedQuery} annotation. The name of the named query is: {@code Todo.findBySearchTermNamed}.
* @param searchTerm The given search term.
* @param pageRequest The information of the given page.
* @return A page of todo entries whose title or description contains with the given search term. The content of
* the returned page depends from the page request given as a method parameter.
*/
Page < Todo > findBySearchTermNamed(@Param("searchTerm") String searchTerm, Pageable pageRequest);
/**
* This query method invokes the named SQL query that is configured in the {@code Todo} class by using
* the {@code @NamedNativeQuery} annotation. The name of the named native query is: {@code Todo.findBySearchTermNamedNative}.
* @param searchTerm The given search term.
* @return A list of todo entries whose title or description contains with the given search term. The returned
* todo entries are sorted in alphabetical order by using the title of the todo entry.
*/
List < Todo > findBySearchTermNamedNative(@Param("searchTerm") String searchTerm);
/**
* This query method reads the named JPQL query from the {@code META-INF/jpa-named-queries.properties} file.
* The name of the invoked query is: {@code Todo.findBySearchTermNamedFile}.
* @param searchTerm The given search term.
* @param pageRequest The information of the given page.
* @return A page of todo entries whose title or description contains with the given search term. The content of
* the returned page depends from the page request given as a method parameter.
*/
Page < Todo > findBySearchTermNamedFile(@Param("searchTerm") String searchTerm, Pageable pageRequest);
![Page 54: JPA : Java Persistence APIbayoudhi-chaouki.e-monsite.com/medias/files/jpa-spring-data.pdf · JPA, the Java Persistence API, a specification for managing relational databases using](https://reader034.vdocuments.net/reader034/viewer/2022042600/5f4718e01cb50a1e014ff4c4/html5/thumbnails/54.jpg)
54
Example 2 : Spring Data JPA - TodoRepository.java
/**
* This query method reads the named native query from the {@code META-INF/jpa-named-queries.properties} file.
* The name of the invoked query is: {@code Todo.findBySearchTermNamedNativeFile}.
* @param searchTerm The given search term.
* @return A list of todo entries whose title or description contains with the given search term. The returned
* todo entries are sorted in alphabetical order by using the title of the todo entry.
*/
@Query(nativeQuery = true)
List < Todo > findBySearchTermNamedNativeFile(@Param("searchTerm") String searchTerm);
/**
* This query method reads the named from the {@code META-INF/orm.xml} file. The name of the invoked query
* is: {@code Todo.findBySearchTermNamedOrmXml}.
* @param searchTerm The given search term.
* @param pageRequest The information of the given page.
* @return A page of todo entries whose title or description contains with the given search term. The content of
* the returned page depends from the page request given as a method parameter.
*/
Page < Todo > findBySearchTermNamedOrmXml(@Param("searchTerm") String searchTerm, Pageable pageRequest);
![Page 55: JPA : Java Persistence APIbayoudhi-chaouki.e-monsite.com/medias/files/jpa-spring-data.pdf · JPA, the Java Persistence API, a specification for managing relational databases using](https://reader034.vdocuments.net/reader034/viewer/2022042600/5f4718e01cb50a1e014ff4c4/html5/thumbnails/55.jpg)
55
Example 2 : Spring Data JPA - TodoRepository.java
/**
* This query method reads the named from the {@code META-INF/orm.xml} file. The name of the invoked query
* is: {@code Todo.findBySearchTermNamedNativeOrmXml}.
* @param searchTerm The given search term.
* @return A list of todo entries whose title or description contains the given search term. The returned
* todo entries are sorted in alphabetical order by using the title of the todo entry.
*/
@Query(nativeQuery = true)
List < Todo > findBySearchTermNamedNativeOrmXml(@Param("searchTerm") String searchTerm);
/**
* This query method invokes the JPQL query that is configured by using the {@code @Query} annotation.
* @param searchTerm The given search term.
* @param pageRequest The information of the requested page.
* @return A page of todo entries whose title or description contains with the given search term. The content of
* the returned page depends from the page request given as a method parameter.
*/
@Query("SELECT t FROM Todo t WHERE " +
"LOWER(t.title) LIKE LOWER(CONCAT('%',:searchTerm, '%')) OR " +
"LOWER(t.description) LIKE LOWER(CONCAT('%',:searchTerm, '%'))")
Page < Todo > findBySearchTerm(@Param("searchTerm") String searchTerm, Pageable pageRequest);
![Page 56: JPA : Java Persistence APIbayoudhi-chaouki.e-monsite.com/medias/files/jpa-spring-data.pdf · JPA, the Java Persistence API, a specification for managing relational databases using](https://reader034.vdocuments.net/reader034/viewer/2022042600/5f4718e01cb50a1e014ff4c4/html5/thumbnails/56.jpg)
56
Example 2 : Spring Data JPA - TodoRepository.java
/**
* This query method invokes the JPQL query that is configured by using the {@code @Query} annotation.
* @param searchTerm The given search term.
* @return A list of todo entries whose title or description contains with the given search term. The
* returned todo entries are sorted in alphabetical order by using the title of a todo entry.
*/
@Query("SELECT t FROM Todo t WHERE " +
"LOWER(t.title) LIKE LOWER(CONCAT('%',:searchTerm, '%')) OR " +
"LOWER(t.description) LIKE LOWER(CONCAT('%',:searchTerm, '%')) " +
"ORDER BY t.title ASC")
List < Todo > findBySearchTermSortedInQuery(@Param("searchTerm") String searchTerm);
/**
* This query method invokes the SQL query that is configured by using the {@code @Query} annotation.
* @param searchTerm The given search term.
* @return A list of todo entries whose title or description contains with the given search term. The
* returned todo entries are sorted in alphabetical order by using the title of a todo entry.
*/
@Query(value = "SELECT * FROM todos t WHERE " +
"LOWER(t.title) LIKE LOWER(CONCAT('%',:searchTerm, '%')) OR " +
"LOWER(t.description) LIKE LOWER(CONCAT('%',:searchTerm, '%')) " +
"ORDER BY t.title ASC",
nativeQuery = true
)
List < Todo > findBySearchTermNative(@Param("searchTerm") String searchTerm);
![Page 57: JPA : Java Persistence APIbayoudhi-chaouki.e-monsite.com/medias/files/jpa-spring-data.pdf · JPA, the Java Persistence API, a specification for managing relational databases using](https://reader034.vdocuments.net/reader034/viewer/2022042600/5f4718e01cb50a1e014ff4c4/html5/thumbnails/57.jpg)
57
Example 2 : Spring Data JPA - TodoRepository.java
Optional < Todo > findOne(Long id);
void flush();
Todo save(Todo persisted);
}