spring之使用 Spring Data JPA 从数据库设置 transient 值

Renyi-Fan 阅读:132 2025-02-15 21:57:57 评论:0

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

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

@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 子句这是不允许的,当前示例不起作用。

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

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

先感谢您。

请您参考如下方法:

我认为你可以做这样的事情。通过使用 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; 
   } 
} 


标签:Spring
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号