使用Spring Data JPA从数据库设置瞬态值 [英] Set transient value from database with Spring Data JPA

查看:123
本文介绍了使用Spring Data JPA从数据库设置瞬态值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I wonder if there is a way to retrieve a generated value from database as an extra column and map it to a transient value.

我会尽力解释自己,我希望像这样:

I'll try to explain myself, I wish something like this:

@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子句,并且当前示例不起作用.

I'm using @Query annotation for simplicity, so I'm limited because of that. HAVING clause it's not allowed, and the current example it's not working.

因为我需要存储在数据库中的值以及从服务传递的值,所以我需要从数据库中进行过滤.

As I need the value stored in database, and the value passed from service, I'm in need to do the filtering from database.

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

Or maybe it's there another approach to doing this?

谢谢.

推荐答案

我认为您可以做这样的事情.通过使用JPQL的新功能,使用其他构造函数创建新实例.

I think you could do something like this. Create a new instance using a different constructor by using JPQL New feature.

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

@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")

只需添加如下构造函数即可.

Just add the constructor as below.

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 Data JPA从数据库设置瞬态值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆