Skip to content

JPA Repository

quad22-dev edited this page Jul 11, 2024 · 2 revisions

JPA Repository

A JPA repository is an interface that extends one of the Spring Data repository interfaces such as JpaRepository, CrudRepository, or PagingAndSortingRepository. The JpaRepository interface provides JPA-related methods such as flushing the persistence context and deleting records in a batch.

Creating a JPA Repository

To create a JPA repository, follow these steps:

  1. Define an Entity:

    import javax.persistence.Entity;
    import javax.persistence.Id;
    
    @Entity
    public class User {
        @Id
        private Long id;
        private String name;
        private String email;
    
        // Getters and setters
    }
  2. Create the Repository Interface:

    import org.springframework.data.jpa.repository.JpaRepository;
    
    public interface UserRepository extends JpaRepository<User, Long> {
    }

Custom Query Methods

Spring Data JPA allows you to define query methods by simply declaring methods in the repository interface. You can use naming conventions to create queries automatically.

findBy Methods

These methods allow you to search for records based on specific attributes.

  • Example:
    import java.util.List;
    
    public interface UserRepository extends JpaRepository<User, Long> {
        List<User> findByName(String name);
        List<User> findByEmail(String email);
    }

In this example, Spring Data JPA will automatically create the necessary queries to find User entities by their name or email.

findIn Methods

To find records where an attribute matches any value in a given list, use the In keyword.

  • Example:
    import java.util.List;
    
    public interface UserRepository extends JpaRepository<User, Long> {
        List<User> findByNameIn(List<String> names);
    }

In this example, findByNameIn will generate a query to find all User entities where the name is in the provided list of names.

Additional Custom Query Methods

You can also create more complex queries using JPQL (Java Persistence Query Language) or native SQL.

Using JPQL

  • Example:
    import org.springframework.data.jpa.repository.Query;
    import org.springframework.data.repository.query.Param;
    
    public interface UserRepository extends JpaRepository<User, Long> {
        @Query("SELECT u FROM User u WHERE u.email = :email")
        User findByEmailAddress(@Param("email") String email);
    }

Using Native SQL

  • Example:
    import org.springframework.data.jpa.repository.Query;
    import org.springframework.data.repository.query.Param;
    
    public interface UserRepository extends JpaRepository<User, Long> {
        @Query(value = "SELECT * FROM User WHERE email = :email", nativeQuery = true)
        User findByEmailNative(@Param("email") String email);
    }

Entity Definition

Let's use a User entity with additional attributes for demonstration:

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class User {
    @Id
    private Long id;
    private String name;
    private String email;
    private Integer age;
    private String city;

    // Getters and setters
}

Repository Interface

Here's the repository interface with various query methods:

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;

public interface UserRepository extends JpaRepository<User, Long> {

    // Simple findBy methods
    List<User> findByName(String name);
    List<User> findByEmail(String email);
    List<User> findByAge(Integer age);
    
    // Using findIn
    List<User> findByNameIn(List<String> names);
    List<User> findByEmailIn(List<String> emails);
    List<User> findByAgeIn(List<Integer> ages);
    
    // Using findAllBy
    List<User> findAllByCity(String city);
    
    // Using findFirstBy
    User findFirstByOrderByAgeAsc();
    User findFirstByOrderByAgeDesc();
    
    // Using JPQL
    @Query("SELECT u FROM User u WHERE u.city = :city")
    List<User> findUsersInCity(@Param("city") String city);

    // Using Native SQL
    @Query(value = "SELECT * FROM User WHERE city = :city", nativeQuery = true)
    List<User> findUsersInCityNative(@Param("city") String city);

    // Complex JPQL query
    @Query("SELECT u FROM User u WHERE u.age > :age AND u.city = :city")
    List<User> findUsersByAgeAndCity(@Param("age") Integer age, @Param("city") String city);
    
    // Complex Native SQL query
    @Query(value = "SELECT * FROM User WHERE age > :age AND city = :city", nativeQuery = true)
    List<User> findUsersByAgeAndCityNative(@Param("age") Integer age, @Param("city") String city);
}

Detailed Explanation of Methods

  1. Simple findBy Methods:

    List<User> findByName(String name);
    List<User> findByEmail(String email);
    List<User> findByAge(Integer age);
  2. findIn Methods:

    List<User> findByNameIn(List<String> names);
    List<User> findByEmailIn(List<String> emails);
    List<User> findByAgeIn(List<Integer> ages);
  3. findAllBy Methods:

    List<User> findAllByCity(String city);
  4. findFirstBy Methods:

    User findFirstByOrderByAgeAsc();
    User findFirstByOrderByAgeDesc();
  5. JPQL Queries:

    @Query("SELECT u FROM User u WHERE u.city = :city")
    List<User> findUsersInCity(@Param("city") String city);
    
    @Query("SELECT u FROM User u WHERE u.age > :age AND u.city = :city")
    List<User> findUsersByAgeAndCity(@Param("age") Integer age, @Param("city") String city);
  6. Native SQL Queries:

    @Query(value = "SELECT * FROM User WHERE city = :city", nativeQuery = true)
    List<User> findUsersInCityNative(@Param("city") String city);
    
    @Query(value = "SELECT * FROM User WHERE age > :age AND city = :city", nativeQuery = true)
    List<User> findUsersByAgeAndCityNative(@Param("age") Integer age, @Param("city") String city);

Usage Examples

Here are some examples of how you might use these methods in a service class:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    public List<User> getUsersByName(String name) {
        return userRepository.findByName(name);
    }

    public List<User> getUsersByEmails(List<String> emails) {
        return userRepository.findByEmailIn(emails);
    }

    public List<User> getUsersInCity(String city) {
        return userRepository.findUsersInCity(city);
    }

    public User getYoungestUser() {
        return userRepository.findFirstByOrderByAgeAsc();
    }

    public List<User> getUsersByAgeAndCity(int age, String city) {
        return userRepository.findUsersByAgeAndCity(age, city);
    }
}
Clone this wiki locally