我创建了这两个实体来展示我的问题:
OwnerEntity.java:
@Entity
public class OwnerEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Size(min = 1)
@OneToMany(mappedBy = "ownerEntity", cascade = CascadeType.ALL)
private Set<ChildEntity> childEntities = new HashSet<>();
}
ChildEntity.java:
@Entity
public class ChildEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@NotNull
@ManyToOne(optional = false)
private OwnerEntity ownerEntity;
public ChildEntity() {
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public OwnerEntity getOwnerEntity() {
return ownerEntity;
}
public void setOwnerEntity(OwnerEntity ownerEntity) {
this.ownerEntity = ownerEntity;
}
}
我希望编写一个查询,可以显示OwnerEntity和一个已连接的ChildEntity的信息。我创建了一个投影:
OwnerEntityProjection.java:
public interface OwnerEntityProjection {
Long getId();
String getName();
}
我的JpaRepository:
public interface OwnerEntityRepository extends JpaRepository<OwnerEntity, Long> {
@Query(" SELECT " +
" ownerEntity.id AS id, " +
" childEntities.name AS name " +
" FROM OwnerEntity ownerEntity " +
" JOIN ownerEntity.childEntities childEntities ")
// There must be also WHERE clause, but for demonstration it is omitted
Slice<OwnerEntityProjection> findAllPaginated(Pageable pageRequest);
}
现在当我运行这个简单的测试:
@Test
public void findAllPaginatedTest() {
Pageable pageRequest = new PageRequest(0, 3, Sort.Direction.ASC, "name");
Slice<OwnerEntityProjection> OwnerEntityProjectionsPaginated =
ownerEntityRepository.findAllPaginated(pageRequest);
}
我得到了以下错误:
org.hibernate.QueryException: could not resolve property: name of: com.example.domain.OwnerEntity
我还检查了日志中生成的JQPL:
... order by ownerEntity.name asc
您可以看到Spring Data Jpa在FROM子句中添加了第一个实体别名。我发现如果我将PageRequest更改为:
new PageRequest(0, 3, Sort.Direction.ASC, "childEntities.name");
它能够正常运行,但我不想在JPQL查询中传递具有别名的排序属性。我想传递直接存在于仓库方法返回的投影中的属性。如果我手动在JPQL查询中编写ORDER BY,就像这样:
... ORDER BY name ASC
然后,这个查询也可以正常运行,因为我可以在ORDER BY子句中引用SELECT子句中的别名。 有没有办法告诉Spring Data Jpa在排序时不需要在FROM或JOIN子句中附加别名?类似于这样:
new PageRequest(0, 3, Sort.Direction.ASC, "name") ===> ORDER BY name asc