Ressources
Spring Data JPA agit comme une couche au-dessus de JPA et vous offre deux façons de dĂ©finir votre requĂȘte :
- Vous pouvez laisser Spring Data JPA dĂ©river la requĂȘte Ă partir du nom dâune mĂ©thode.
- Vous pouvez dĂ©finir votre propre requĂȘte JPQL ou native en utilisant une annotation
@Query
Depuis une méthode
Supposons une classe Produit qui dispose du champs nom et puis nous définissons la méthode suivante
public interface ProduitRepository extends JpaRepository<Produit, Long> {
List<Produit> findByNom(String nom);
}Spring Data JPA implémente automatiquement cette méthode sans aucune écriture SQL manuelle en
SELECT * FROM produit WHERE nom = :nomRespecter les conventions
Nous devons juste prĂȘter garde Ă respecter les conventions dĂ©finies par Spring Data JPA, disponible ici
| Keyword | SQL Equivalent | Exemple | SQL Généré |
|---|---|---|---|
And | AND | findByNomAndPrix | WHERE nom = ? AND prix = ? |
Or | OR | findByNomOrCategorie | WHERE nom = ? OR categorie = ? |
Between | BETWEEN | findByPrixBetween | WHERE prix BETWEEN ? AND ? |
LessThan | < | findByPrixLessThan | WHERE prix < ? |
GreaterThan | > | findByPrixGreaterThan | WHERE prix > ? |
Like | LIKE | findByNomLike | WHERE nom LIKE ? |
NotLike | NOT LIKE | findByNomNotLike | WHERE nom NOT LIKE ? |
IsNull | IS NULL | findByDescriptionIsNull | WHERE description IS NULL |
IsNotNull | IS NOT NULL | findByDescriptionIsNotNull | WHERE description IS NOT NULL |
OrderBy | ORDER BY | findByCategorieOrderByNomAsc | ORDER BY nom ASC |
Depuis @Query
public interface UserRepository extends JpaRepository<User, Long> {
@Query("select u from User u where u.emailAddress = ?1")
User findByEmailAddress(String emailAddress);
}Utilisation du LIKE
public interface UserRepository extends JpaRepository<User, Long> {
@Query("select u from User u where u.firstname like %?1")
List<User> findByFirstnameEndsWith(String firstname);
}