使用 Spring Data JPA 从数据库设置瞬态值

qga*_*ian 4 spring jpa spring-data spring-data-jpa

我想知道是否有办法从数据库中检索生成的值作为额外的列并将其映射到瞬态值。

我会试着解释自己,我希望是这样的:

@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);
}
Run Code Online (Sandbox Code Playgroud)

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

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

或者也许有另一种方法可以做到这一点?

先感谢您。

Koi*_*oer 5

我认为你可以做这样的事情。通过使用 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;
   }
}
Run Code Online (Sandbox Code Playgroud)