问题
I have rest repository with 2 entities and projection:
@Entity
public class Person {
@Id
@GeneratedValue
private Long id;
String name;
@ManyToOne
Language language;
}
@Entity
public class Language {
@Id
@GeneratedValue
private Long id;
private String name;
}
public interface PersonRepository extends PagingAndSortingRepository<Person, Long> {
}
@Projection(name = "details", types = {Person.class})
interface PersonProjection {
Long getId();
String getName();
@Value("#{target.language.name}")
String getLanguage();
}
When I'm trying to sort it by language field
/api/persons/?projection=details&sort=language
it produce SQL that trying to sort it by language.id
select person0_.id as i... order by language1_.id asc limit ?
Is there a way to tell Spring Data, JPA to use different default property for sorting without explicitly specifying it in url?
回答1:
Spring data-rest as you configured it uses property traversal on your entity objects. In your case, for Person and Language you have a name clash on the property "name". In order to solve this issue your sort param should reference the correct property, i.e: For sorting by language name your url should be like /api/persons/?projection=details&sort=language_name For sorting by person's name your url parameter shoud look /api/persons/?projection=details&sort=person_name
回答2:
First override the findAll()
method in your PersonRepository
interface:
public interface PersonRepository extends PagingAndSortingRepository<Person, Long> {
@Override
@Query
public Iterable<User> findAll();
}
Then add a named query to your User
entity class:
@Entity
@NamedQuery(name = "User.findAll", query="select p from Person p order by p.language.name")
public class Person {
@Id
@GeneratedValue
private Long id;
String name;
@ManyToOne
Language language;
}
来源:https://stackoverflow.com/questions/40825366/define-sort-property-for-referenced-field-during-order-by-in-jpql