简体   繁体   中英

How do I dynamically sort nested entities using Spring Data's Sort?

I have the following JPQL query in a Spring Data Repository:

public interface CarRepository extends Repository<Car, Integer> {
    
    @Query("select distinct c.model from Car c where c.id in :ids")
    Set<Model> findDistinctModelByIdIn(@Param("ids") Set<Integer> ids, Sort sort);
}

A client calls the query as follows (which is exposed via Spring Data REST):

http://localhost:8080/api/cars/search/findDistinctModelByIdIn?ids=1,33,55,43&sort=model.name,desc

However, the results are returned unsorted. How can I sort based on the client sort request parameter?

Does Spring only sort on the domain type the repository manages (eg, only Car not Model )?

Update

Here is my domain model:

@Entity
@Data
public class Car {
    @Id
    private Long id;
    
    @ManyToOne
    private Model model;
}

@Entity
@Data
public class Model {
    @Id
    private Long id;

    private String name;
}
 

Does Spring only sort on the domain type the repository manages (eg, only Car not Model)?

Actually, does. I've modeled a case like yours and didn't face any problems. Here it is . What if the cornerstone is in the Spring s version? It often happens that in some versions the internal implementation is very different...

Spring supports that for sure, the only thing is that it performs a crossjoin, which means you'll lose the entities with a null Model from the result.

To debug this I would suggest you add this config:

spring:
  jpa:
    show-sql: true

Then you can check in the console/ logs the executed db query and see if the sorting was there, hence find whether the problem is in the query generation or in the data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM