spring data jpa生成的错误sql查询

时间:2017-12-27 20:50:08

标签: spring-data-jpa spring-restcontroller

鉴于下面的存储库

@Repository
public interface DashboardRepository
       extends PagingAndSortingRepository<Dashboard, Long> {
    @Query("SELECT " +
           "    d " +
           "FROM " + 
           "    Dashboard d " + 
           "WHERE " + 
           "    d.branchUserId= :userId " +
           "OR  d.restUserId = :userId " + 
           "ORDER BY " +
           "    d.orderId DESC")
    Page<Dashboard> findByBranchUserIdOrRestUserId(@Param("userId") Long userId, Pageable pageable);
}

当我拨打findByBranchUserIdOrRestUserId时,我看到生成了以下查询:

SELECT
    COUNT(dashboard0_.ORDER_ID) AS col_0_0_
FROM
    DAILY_ORDERS dashboard0_
WHERE
    dashboard0_.BRANCH_USER_ID=?
OR dashboard0_.REST_USER_ID=?

任何线索可能是什么问题?

更新Dashboard实体已映射到数据库视图。当我直接在数据库上执行SELECT * FROM [view name]时,我会返回行。但是,当我执行dashboardRepository.count()时,我得到零。

1 个答案:

答案 0 :(得分:0)

我认为这与Spring推断的“countQuery”

有关

在文档中是关于分页和自定义@Queries

的讨论
public interface UserRepository extends JpaRepository<User, Long> {

  @Query(value = "SELECT * FROM USERS WHERE LASTNAME = ?1",
    countQuery = "SELECT count(*) FROM USERS WHERE LASTNAME = ?1",
    nativeQuery = true)
  Page<User> findByLastname(String lastname, Pageable pageable);
}

参考:https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods.at-query