Robert
Robert

Reputation: 337

Spring Boot JPA Projection don't work with Specification and Pagable as expected

I have simple entity. When I invoke findPageableCommunityAccess from below examples I'm receiving result that look like CommunityAccess (full object) instead CommunityAccessProjection. Do Projections works correctly with Specification and Pageable?

@Entity
public class Community {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    @Column(nullable = false)
    private Long id;

    @NotBlank(message = "validation.community.name.notblank")
    @Column(columnDefinition = "TEXT")
    private String name;

    @NotBlank(message = "validation.community.description.notblank")
    @Column(columnDefinition = "TEXT")
    private String description;

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true)
    @JoinColumn(name = "community_id")
    @JsonIgnore
    private Set<CommunityAccess> communityAccesses = new HashSet<>();
}

CommunityAccess

public class CommunityAccess {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    @Column(nullable = false)
    private Long id;

    @ManyToOne
    @JoinColumn(name = "user_id")
    private User user;

    @Enumerated(EnumType.STRING)
    private Role role;

    @ManyToOne
    @JsonIgnore
    private Community community;
}

User

@Entity
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    @Column(nullable = false)
    private Long id;

    @Column(unique = true, nullable = false)
    @Email(message = "error.email.format", regexp = "^[a-zA-Z0-9_!#$%&'*+/=?`{|}~^.-]+@[a-zA-Z0-9.-]+$")
    @NotBlank(message = "validation.user.email.notblank")
    private String email;

    @Column(nullable = false)
    @NotBlank(message = "validation.user.username.notblank")
    private String username;

    @Column(nullable = false)
    @NotBlank(message = "validation.user.firstname.notblank")
    private String firstName;
}

CommunityAccessRepository

@Repository
public interface CommunityAccessRepository extends JpaRepository<CommunityAccess, Long>, JpaSpecificationExecutor<CommunityAccess> {
    Page<CommunityAccessProjection> findAll(Specification specification, Pageable pageable);
}

CommunityService

    public Page<CommunityAccessProjection> findPageableCommunityAccess(Long id, String search, Pageable pageable) {
        Community community = findBy(id);
        Specification<CommunityAccessProjection> spec = GenericSearchQueryConverter.convert(search);

        return communityAccessRepository.findAll(Specification.allOf(spec, (root, query, cb) -> cb.equal(root.get("community"), community)), pageable);
    }

Projection

public interface CommunityAccessProjection {
    Long getId();
    String getRole();
}

Upvotes: 0

Views: 23

Answers (0)

Related Questions