spring-projects / spring-data-jpa

Simplifies the development of creating a JPA-based data access layer.
https://spring.io/projects/spring-data-jpa/
Apache License 2.0
2.92k stars 1.39k forks source link

Different `property` is used in `Sort.Order` method #3477

Closed IlyaLisov closed 1 month ago

IlyaLisov commented 1 month ago

I have two entities

@Entity
@Table(name = "articles")
public final class Article {
    ...
    private int viewsAmount;

    public enum SortType {
        ...,
        VIEWS_AMOUNT
    }
}
@Entity
@Table(name = "employees")
public final class Employee {
    ...
    private int viewsAmount;

    public enum SortType {
        ...,
        VIEWS_AMOUNT
    }
}

Next, I want to sort this entities by using Sort.Order object:

public Pageable getPageable() {
    Sort.Order order = Sort.Order.desc("views_amount");
    return PageRequest.of(
            this.pageId - 1,
            this.perPage,
            Sort.by(order)
    );
}

When I call repository method with custom @Query, I get it working. Entities are loaded.

@Query(value = """
        SELECT em.*
        FROM employees em
        WHERE em.status = :status
        AND em.type LIKE coalesce(:type, '%%')
        """, nativeQuery = true)
Page<Employee> findAllByStatusAndType(
        @Param("status") String status,
        @Param("type") String type,
        Pageable page
);

When I call repository method without custom @Query, it is not working with exception No property 'views' found for type 'Article'. I don't even understand why it is views here in the exception.

Page<Article> findAllByStatus(
        Status status,
        Pageable page
);

It works if I change order object to Sort.Order.desc("viewsAmount") as it is names in @Entity.

In the documentation I did not find what does property mean in Sort.Order methods. I thought it means database column names, but as I see here, it can also mean @Entity field.

quaff commented 1 month ago

Could you provide a minimal sample project?

mp911de commented 1 month ago

This is correct and expected. Sort.Order.desc("views_amount"); would refer to a nested property amount in the views property of Article or Employee. Sort refers always to property names unless the query is a native one. Spring Data uses _ as separator to force property name splitting.