我有一个运行Spring Data + Hibernate的应用程序和以下查询:
@Query(value = "SELECT NEW com.foo.dto.OfertaBancoDto(y,(SELECT CASE a.id WHEN NULL THEN 0 ELSE 1 END FROM Banco b LEFT JOIN b.blackList a)) FROM Oferta y WHERE y.id IN (SELECT DISTINCT (o.id) FROM Oferta o WHERE o.status IN (?1) AND o.dataRemocao IS NULL AND o.status = 1)",
countQuery = "SELECT COUNT(y) FROM Oferta y WHERE y.id IN (SELECT DISTINCT (o.id) FROM Oferta o WHERE o.status IN (?1) AND o.dataRemocao IS NULL AND o.status = 1)")
Page<OfertaBancoDto> randomSearch(Set<StatusOferta> filtroStatus, Pageable pageable);
每次我尝试发出一个orderby:
new PageRequest(0, 10, new Sort(Direction.ASC, "titulo"));
结果查询是(b.titulo是问题,因为b表示错误的表):
SELECT NEW com.foo.dto.OfertaBancoDto(y,(SELECT CASE a.id WHEN NULL THEN 0 ELSE 1 END FROM com.foo.entity.Banco b LEFT JOIN b.blackList a)) FROM com.foo.entity.Oferta y WHERE y.id IN (SELECT DISTINCT (o.id) FROM com.foo.entity.Oferta o WHERE o.status IN (?1) AND o.dataRemocao IS NULL AND o.status = 1) order by b.titulo asc
正确的查询应该是:
SELECT NEW com.foo.dto.OfertaBancoDto(y,(SELECT CASE a.id WHEN NULL THEN 0 ELSE 1 END FROM com.foo.entity.Banco b LEFT JOIN b.blackList a)) FROM com.foo.entity.Oferta y WHERE y.id IN (SELECT DISTINCT (o.id) FROM com.foo.entity.Oferta o WHERE o.status IN (?1) AND o.dataRemocao IS NULL AND o.status = 1) order by y.titulo asc
如何指定orderby应该过滤的表?
答案 0 :(得分:0)
您的存储库的签名是什么?看起来应该是这样的:
public interface FooRepo extends JpaRepository<T, ID> {
....
}
我怀疑你使用过Banco for T.所以要解决这个问题,你可以试试2个选项:
1)将方法移动到Oferta的存储库
2)将此方法移至Custom Repository(我认为这样更好)http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.custom-implementation
答案 1 :(得分:0)
我猜你的 pageable 是这样的:
Sort sort = new Sort(Sort.Direction.DESC, "id");
Pageable pageable = new PageRequest(offset, limit,sort)
不要使用排序更改您的可分页,例如:
// Sort sort = new Sort(Sort.Direction.DESC, "id");
Pageable pageable = new PageRequest(offset, limit)
使用sql实现按功能排序:
@Query(value = "SELECT NEW com.foo.dto.OfertaBancoDto(y,(SELECT CASE a.id WHEN NULL THEN 0 ELSE 1 END FROM Banco b LEFT JOIN b.blackList a)) FROM Oferta y WHERE y.id IN (SELECT DISTINCT (o.id) FROM Oferta o WHERE o.status IN (?1) AND o.dataRemocao IS NULL AND o.status = 1) order by y.titulo asc ",
countQuery = "SELECT COUNT(y) FROM Oferta y WHERE y.id IN (SELECT DISTINCT (o.id) FROM Oferta o WHERE o.status IN (?1) AND o.dataRemocao IS NULL AND o.status = 1)")
Page randomSearch(Set filtroStatus, Pageable pageable);