spring子句中的jpa max aggregate函数

时间:2015-07-30 09:53:47

标签: jpa eclipselink spring-data-jpa

我对此查询有错误

 @Repository
    public interface DefinedAbsenceRepository extends
            JpaRepository<DefinedAbsence, Long>,
            JpaSpecificationExecutor<DefinedAbsence> {  @Query("select da from defined_absence da where da.length=?1 and max (da.from, ?2) < min (da.to , ?3) " )
        List<DefinedAbsence> getLongDefinedAbsenceWithinPeriod(
                AbsenceLength length, LocalDateTime from, LocalDateTime to);
    }`

这是班级

 public class DefinedAbsence extends BaseBean {
        public static enum AbsenceJustification {
            JUSTIFIED, UNJUSTIFIED
        }
        private LocalDateTime from;
        private LocalDateTime to;
        private AbsenceLength length;
        private String description;
    //geter()+setter()
    }

我在joda时间使用转换器

生成错误Caused by: Exception [EclipseLink-0] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.JPQLException Exception Description: Syntax error parsing [select da from defined_absence da where da.length=?1 and max (da.from, ?2) < min (da.to , ?3) ]. [59, 70] The right expression is not a valid expression. [72, 95] The query contains a malformed ending.

2 个答案:

答案 0 :(得分:1)

您混淆编程语言中的for (i = 1980; i <= Year1; i++) { } 函数,它比较两个值并返回更大的值,以及来自SQL的max(a, b)聚合函数,它从所有结果行中找到最大值(可能对于单个表达式进行分组。

要在SQL中使用MAX(expression)max(a, b),您必须使用min(a, b)

CASE

答案 1 :(得分:0)

这对我来说很好:

@Repository
public interface DefinedAbsenceRepository extends
        JpaRepository<DefinedAbsence, Long>,
        JpaSpecificationExecutor<DefinedAbsence> {

    @Query("select da from defined_absence da where da.length = ?1 and "
            + "(CASE WHEN da.from > ?2 THEN  da.from ELSE  ?4 END) < "
            + "(CASE WHEN da.to < ?3 THEN  da.to ELSE  ?5 END) ")
    List<DefinedAbsence> get(AbsenceLength length, LocalDateTime from,
            LocalDateTime to,Long f ,Long t);
}

我用Long属性替换了“ELSE?2”和“ELSE?3”因为我有一个类型为LocalDateTime的错误我不知道为什么eclipselink无法通过转换器(LocalDateTime到Long)

public List<DefinedAbsence> get(LocalDateTime from, LocalDateTime to) {
        return definedAbsenceRepository.get(AbsenceLength.LONG, from, to,
                from.toDateTime().getMillis(), to.toDateTime().getMillis());
    }