Sobes.tech
Junior — Middle

How to implement data search using Spring Data JPA based on specified conditions?

sobes.tech AI

Answer from AI

In Spring Data JPA, there are several approaches to search for data based on specified conditions:

  1. Repository methods with named queries — create methods in the repository interface with names reflecting the search conditions, for example:
public interface UserRepository extends JpaRepository<User, Long> {
    List<User> findByLastNameAndAge(String lastName, int age);
}
  1. @Query with JPQL or native SQL — write the query manually:
@Query("SELECT u FROM User u WHERE u.lastName = :lastName AND u.age = :age")
List<User> findUsers(@Param("lastName") String lastName, @Param("age") int age);
  1. Specification API — for dynamic construction of conditions:
public class UserSpecification implements Specification<User> {
    private String lastName;
    private Integer age;

    public UserSpecification(String lastName, Integer age) {
        this.lastName = lastName;
        this.age = age;
    }

    @Override
    public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
        List<Predicate> predicates = new ArrayList<>();
        if (lastName != null) {
            predicates.add(cb.equal(root.get("lastName"), lastName));
        }
        if (age != null) {
            predicates.add(cb.equal(root.get("age"), age));
        }
        return cb.and(predicates.toArray(new Predicate[0]));
    }
}

And then use it in the repository:

List<User> users = userRepository.findAll(new UserSpecification("Smith", 30));

Thus, the choice of method depends on the complexity and dynamism of the search conditions.