首页 > 解决方案 > 在 Hibernate 原生查询中排序

问题描述

我正在尝试使用以下代码构建参数化顺序并按本机查询排序:

@Query(value = "SELECT e.first_name as firstName, e.last_name as lastName, jh.start_date as startDate, jh.end_date as endDate, " +
        "j.job_title as jobName, d.department_name as departmentName FROM JOB_HISTORY jh " +
        "JOIN JOBS j ON jh.JOB_ID = j.JOB_ID " +
        "JOIN DEPARTMENTS d ON JH.DEPARTMENT_ID = d.DEPARTMENT_ID " +
        "JOIN EMPLOYEES e ON jh.EMPLOYEE_ID = e.EMPLOYEE_ID " +
        "ORDER BY :sortBy :orderBy", nativeQuery = true)
List<EmployeeJobView> getAllEmployeeJob(String sortBy, String orderBy);

这给了我一个例外,并且不是按 HQL 进行订购的正确方法。

这是投影界面

public interface EmployeeJobView {

    @Value("#{target.firstName + ' ' + target.lastName}")
    String getFullName();
    
    Timestamp getStartDate();
    Timestamp getEndDate();
    String getJobName();
    String getDepartmentName();
}

正确的方法是什么?

标签: sqlspringhibernatejpa

解决方案


@Query(...
"ORDER BY :sortBy :orderBy", nativeQuery = true)
List<EmployeeJobView> getAllEmployeeJob(@Param("sortBy") String sortBy, @Param("orderBy") String orderBy);

使用命名参数时必须指定 @Param 名称。您还可以使用未命名的参数,例如:

@Query(...
"ORDER BY ?1 ?2", nativeQuery = true)
List<EmployeeJobView> getAllEmployeeJob(String sortBy, String orderBy);

推荐阅读