使用native = true的JPA @Query问题

时间:2015-05-28 05:51:08

标签: java jpa

我有这个奇怪的问题,我无法修复,也不确定出了什么问题。我有以下JPA查询,

@Query(nativeQuery=true, value = "select new com.mypackage.StudentDetailsDTO(e.STUDENT_ID as studentId, e.SUBJECT_ID as subjectId, e.SUBJECT_TYPE as subjectType, "+
"e.RESULT_STATUS as resultStatus, nvl(e.ASSIGNED_STUDENT_ID, -1) as assignedStudentId, nvl(e.TAKEN_BY_STUDENT_ID, -1) as takenByStudentId , count(1) as totalCount) from STUDENT e "
        + "WHERE e.STUDENT_ROLLNO = :studentRollNumber AND e.EXAM_TIME between :startTime AND :endTime ")
public List<StudentDetailsDTO> fetchStudentDetailsUsingGroupBy(@Param("studentRollNumber") String iStudentRollNumber, @Param("startTime") Date iStartTime, @Param("endTime") Date iEndTime);

在oracle上触发时,这是被触发的查询,

select
   new com.mypackage.StudentDetailsDTO(e.STUDENT_ID as studentId,
   e.SUBJECT_ID as subjectId,
   e.SUBJECT_TYPE as subjectType,
   e.RESULT_STATUS as resultStatus,
   nvl(e.ASSIGNED_STUDENT_ID,
   -1) as assignedStudentId,
   nvl(e.TAKEN_BY_STUDENT_ID,
   -1) as takenByStudentId ,
   count(1) as totalCount) 
from
   STUDENT e 
WHERE
   e.STUDENT_ROLLNO = ? 
   AND e.EXAM_TIME between ? AND ? 
GROUP BY
   e.STUDENT_ID,
   e.SUBJECT_ID,
   e.SUBJECT_TYPE,
   e.RESULT_STATUS,
   nvl(e.ASSIGNED_STUDENT_ID,
   -1),
   nvl(e.TAKEN_BY_STUDENT_ID,
   -1)

这是DTO的构造函数,用于映射,

public StudentDetailsDTO(long studentId, long subjectId, String subjectType, String resultStatus, String assignedStudentId, String takenByStudentId, int totalCount) {
       this.studentId = studentId;
       this.subjectId = subjectId;
       this.subjectType = subjectType;
       this.resultStatus = resultStatus;
       this.assignedStudentId = assignedStudentId;
       this.takenByStudentId = takenByStudentId;
       this.totalCount = totalCount;   
   }

每当我遇到异常时,

java.sql.SQLSyntaxErrorException: ORA-00923: FROM keyword not found where expected

任何帮助都将受到赞赏,我正在尝试这个很长时间,但没有运气。

1 个答案:

答案 0 :(得分:2)

您似乎正在使用Spring Data JPA。如果这是正确的,那么你不应该在你的原生查询中调用你的DTO(new com.mypackage.StudentDetailsDTO())的构造函数。您应该编写一个通常的Oracle SQL查询。 Spring Data JPA将根据查询结果自动创建DTO对象。

您的DTO对象中似乎也出现错误。 assignedStudentId和takenByStudentId参数的类型为String,但您的查询会将其选为long