Reputation: 1553
I have two tables in the DB modelling a one-to-one relationship.
The entity class contains something similar to the following:
@Entity
@Table(name = "my_table")
public class MyEntity {
@OneToOne(fetch = FetchType.LAZY)
private MyOtherEntity myOtherEntity
}
Then we have the other class modelling the table with one-to-one relationship:
Entity
@Table(name = "my_other_table")
public class MyOtherEntity {
private String name;
}
And a simplified repository:
public class MyRepository extends PagingAndSortingRepository<MyEntity, Long> {
@Query("SELECT m from MyEntity m INNER JOIN m.myOtherEntity mo")
Page<MyEntity> search(Pageable pageable);
}
This repository is invoked by means of a controller that receives a Pageable
as parameter
How should the query param look when sorting by the name
field in MyOtherEntity
?
I've tried:
sort=myOtherEntity.name
But I get
ORDER BY clause is not in SELECT list
I also don't have the option of printing the generated SQL.
Upvotes: 0
Views: 566
Reputation: 1911
According to the documentation you can disregard JPQL entirely and do something like this :
Page<MyEntity> findAllOrderByMyOtherEntityName();
You should always prefer spring data queries over JPQL if your methods will be readable enough ... its easier and less error-prone. Plus : it decouples strings and program logic, which is what every serious developer should do.
And if you want to create more complex statements : have a look at QueryDSL - it enables you to write typesafe queries whilst having them nicely integrated into spring data JPA, they are officially supported (!)
Upvotes: 1