最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

java - How to use projection with specification in spring data jpa with jpa fluent api - Stack Overflow

programmeradmin3浏览0评论

I am trying to use interface base projection with JPA named methods and add specification, I read github issue and there the mod indicated that as of spring data jpa 3 we can use projection and specification dynamically. I tried different ways but ended up failing

public interface UserRepository extends JpaRepository<User, Long>, JpaSpecificationExecutor<User> {
  User findUserByUserNameIgnoreCase(String username);
  <T> T findById(Long id, Class<T> type);          //works
  <T> List<T> findAllBy(Class<T> type);            //works
 <T> List<T> findAllBy(Specification<?> specification, Class<T> type);  //failed
   List<UserInfoProjection> findAllBy(Specification<User> specification);  // failed

  interface Specs {
    static Specification<User> id(Long id) {
      return (root, query, builder) -> builder.equal(root.get("id"), id);
    }
  }

}

method call

List<UserInfoProjection> up = userRepository.findAllBy(UserRepository.Specs.id(userID));
List<UserInfoProjection> pp = userRepository.findAllBy(UserRepository.Specs.id(userID), UserInfoProjection.class);

Error Log

Caused by: java.lang.IllegalArgumentException: At least 1 parameter(s) provided but only 0 parameter(s) present in query
Caused by: java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.List .backend.user.repository.interfaces.UserRepository.findAllBy(.springframework.data.jpa.domain.Specification); At least 1 parameter(s) provided but only 0 parameter(s) present in query

I am trying to use interface base projection with JPA named methods and add specification, I read github issue and there the mod indicated that as of spring data jpa 3 we can use projection and specification dynamically. I tried different ways but ended up failing

public interface UserRepository extends JpaRepository<User, Long>, JpaSpecificationExecutor<User> {
  User findUserByUserNameIgnoreCase(String username);
  <T> T findById(Long id, Class<T> type);          //works
  <T> List<T> findAllBy(Class<T> type);            //works
 <T> List<T> findAllBy(Specification<?> specification, Class<T> type);  //failed
   List<UserInfoProjection> findAllBy(Specification<User> specification);  // failed

  interface Specs {
    static Specification<User> id(Long id) {
      return (root, query, builder) -> builder.equal(root.get("id"), id);
    }
  }

}

method call

List<UserInfoProjection> up = userRepository.findAllBy(UserRepository.Specs.id(userID));
List<UserInfoProjection> pp = userRepository.findAllBy(UserRepository.Specs.id(userID), UserInfoProjection.class);

Error Log

Caused by: java.lang.IllegalArgumentException: At least 1 parameter(s) provided but only 0 parameter(s) present in query
Caused by: java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.List .backend.user.repository.interfaces.UserRepository.findAllBy(.springframework.data.jpa.domain.Specification); At least 1 parameter(s) provided but only 0 parameter(s) present in query
Share Improve this question asked Feb 17 at 20:21 code_copy_pastecode_copy_paste 112 bronze badges New contributor code_copy_paste is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct. 0
Add a comment  | 

1 Answer 1

Reset to default 0

The error you are seeing is mainly caused by Spring Data JPA not being able to dynamically generate a query for the method when using projections and Specifications together in the format you have provided. While Spring Data JPA 3.0 introduced support for combining projections with specifications, there are certain limitations, especially when trying to combine them dynamically. One of the options to fix is use a Custom Implementation for Combining Specifications with Projections.

Add a Custom Repository Implementation for UserRepository:

    public interface UserRepositoryCustom {
    <T> List<T> findAllBySpecification(Specification<User> specification, Class<T> projectionType);
}

Provide the implementation:

import jakarta.persistence.EntityManager;
import jakarta.persistence.TypedQuery;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Root;
import .springframework.data.jpa.domain.Specification;

import java.util.List;

public class UserRepositoryCustomImpl implements UserRepositoryCustom {

    private final EntityManager entityManager;

    public UserRepositoryCustomImpl(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    @Override
    public <T> List<T> findAllBySpecification(Specification<User> specification, Class<T> projectionType) {
        // Create CriteriaBuilder and CriteriaQuery
        CriteriaBuilder builder = entityManager.getCriteriaBuilder();
        CriteriaQuery<T> query = builder.createQuery(projectionType);

        // Define the root for the query
        Root<User> root = query.from(User.class);

        // Apply Specification filters
        if (specification != null) {
            query.where(specification.toPredicate(root, query, builder));
        }

        // Define query projection
        query.select(builder.construct(projectionType, root.get("id"), root.get("username"))); // Project only fields needed

        // Create and execute the query
        TypedQuery<T> typedQuery = entityManager.createQuery(query);
        return typedQuery.getResultList();
    }
}

Update UserRepository to Extend Custom Interface:

    public interface UserRepository extends JpaRepository<User, Long>, JpaSpecificationExecutor<User>, UserRepositoryCustom {
    User findUserByUserNameIgnoreCase(String username);
    <T> T findById(Long id, Class<T> type);
    <T> List<T> findAllBy(Class<T> type); 
}

To specify which projection to apply, use the findAllBySpecification method with both a Specification and a projection type:

List<UserInfoProjection> projections = userRepository.findAllBySpecification(
    UserRepository.Specs.id(1L), UserInfoProjection.class);
发布评论

评论列表(0)

  1. 暂无评论