【问题标题】:spring JPA query with spel expression for random带有随机拼写表达式的spring JPA查询
【发布时间】:2017-05-08 17:36:21
【问题描述】:

我正在尝试生成一个随机数,以便在 JPA 查询中对数据集进行采样。我已经读过这在任何地方都是完全可能的,但我不断收到错误:

代码:

@Query("select t from Telemetry t where t.id = :id and t.updateTimestamp between :startTime and :endTime and #{ #T(java.lang.Math).random() } < :samplingRate ")
Iterable<Telemetry> findFor(@Param("id") String org, @Param("startTime") Instant startTime, @Param("endTime") Instant endTime, @Param("samplingRate") Float samplingRate);

错误:

org.hibernate.QueryException: 意外字符: '#' [select t from com.mz.rad.dao.Telemetry t 其中 t.id = :id 和 t.updateTimestamp 在 :startTime 和 :endTime 和 #{ #T(java.lang.Math).random() }

深入研究我发现了这个异常:

throw new IllegalArgumentException("Parameter with that position [" + parameterPosition + "] did not exist");

参数位置是 1 还是 2 取决于我使用的语法。

我尝试过使用/不使用哈希。没有运气。我正在使用具有random() 函数的postgres,但它也不喜欢我调用它(这是我的最终目标)。

这个问题是关于使用SPeL,但我只需要一个随机数

【问题讨论】:

    标签: java spring spring-data-jpa jpql spring-el


    【解决方案1】:

    你可以这样试试:#

    select t from Telemetry t where t.id = :id and t.updateTimestamp between :startTime and :endTime and :#{T(java.lang.Math).random()} < :samplingRate
    

    如果没有,则使用?#

    select t from Telemetry t where t.id = :id and t.updateTimestamp between :startTime and :endTime and ?#{T(java.lang.Math).random()} < :samplingRate
    

    【讨论】:

    • 我给了你一个赞成票,但我找到了自己的答案。也需要撞球
    【解决方案2】:

    Answer:

    @Query("select t from Telemetry t where t.id = :id and t.updateTimestamp between :startTime and :endTime and :#{T(java.lang.Math).random()} < :samplingRate ")
    

    帮助提升你的 POM

       <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>1.10.5.RELEASE</version>
        </dependency>
    

    【讨论】:

    • 是的,我让它工作了..现在它随机返回 ALL 或 NO 结果samplingFactor 次:-/新问题
    猜你喜欢
    • 1970-01-01
    • 2019-04-15
    • 2021-01-09
    • 2017-04-21
    • 2021-04-26
    • 2018-09-05
    • 2016-06-11
    • 2023-02-19
    • 1970-01-01
    相关资源
    最近更新 更多