使用Spring Data JPA从数据库中设置临时值

5
我希望有一种方法可以从数据库中检索生成的值作为额外列,并将其映射到瞬态值。
我会尝试解释一下,我希望实现这样的功能:
@Entity
@Table(name = "thing")
public class Thing {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "itemid")
    private Long itemId;

    private String someValue;

    @Transient
    private double distance;

    // constructors, getters, setters, etc.. (include transient methods)
}

Repository("thingRepository")
public interface ThingRepository extends PagingAndSortingRepository<Thing, Long> {

    @Query("SELECT t, cos(someDouble)*sin(:someDouble) AS distance FROM Thing t WHERE someValue = :someValue AND someDouble = :someDouble AND distance > 30")
    Page<Thing> findByParams(@Param("someValue") String someValue, @Param("someDouble") double someDouble, Pageable pageable);
}

为了简单起见,我正在使用@Query注释,因此受限制。HAVING子句是不允许的,当前示例无法工作。

由于我需要存储在数据库中的值和从服务传递的值,因此我需要从数据库中进行过滤。

或者也许有其他方法来做到这一点?

提前致谢。

1个回答

6

我认为你可以这样做。使用JPQL的新功能,通过使用不同的构造函数创建新实例。

@Query("SELECT new Thing(t, cos(t.someDouble)*sin(t.someDouble))FROM Thing t WHERE t.someValue = :someValue AND t.someDouble = :someDouble AND cos(t.someDouble)*sin(t.someDouble)> 30")

只需添加以下构造函数即可。

public class Thing {
  // the code you already had

  public Thing(Thing t, double distance){
     this.itemId = t.itemId;
     this.someValue = t.someValue;
     this.distance = distance;
   }
}

1
谢谢,这个方法很好用。但是使用这个解决方案我要做两次工作,而且实际操作比这个复杂得多。如果我加上一个“AS val”,并且在最后一个where条件中使用“val > 30”,Spring会报错,说第二个参数(你犯了一个错误,在我的例子中我用“someValue column”代替cos,“:someValue”参数代替sin)::someValue不存在。错误信息是:java.lang.IllegalArgumentException: Parameter with that name [:someValue] did not exist. 使用?1也是一样的。不过我还是接受你的解决方案 ;) - qgadrian

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接