Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring实体动态计算字段,参数来自本机查询_Spring_Hibernate_Jdbc - Fatal编程技术网

Spring实体动态计算字段,参数来自本机查询

Spring实体动态计算字段,参数来自本机查询,spring,hibernate,jdbc,Spring,Hibernate,Jdbc,我有一个有点复杂的实体,如下所示(注意有更多字段的超类): 我无法使用@Formula注释我的字段距离,因为查询必须使用参数 如何将SQL查询结果中的字段distance映射到实体字段distance,同时让所有其他映射由Hibernate完成 编辑 基于@gmotux建议,我创建了一个包装器实体 @Entity @SqlResultSetMapping( name="MappingQ", entities={ @EntityRes

我有一个有点复杂的实体,如下所示(注意有更多字段的超类):

我无法使用
@Formula
注释我的字段
距离
,因为查询必须使用参数

如何将SQL查询结果中的字段
distance
映射到实体字段
distance
,同时让所有其他映射由Hibernate完成

编辑 基于@gmotux建议,我创建了一个包装器实体

@Entity
@SqlResultSetMapping(
        name="MappingQ",
        entities={
                @EntityResult(
                        entityClass = QuestionWithDistance.class,
                        fields={
                                @FieldResult(name="distance",column="distance"),
                                @FieldResult(name="question",column="question")})})
public class QuestionWithDistance{
    @Id
    @GeneratedValue
    private String id;

    @OneToOne
    private Question question;
    private double distance;
}
质疑

但它总是以失败告终

org.postgresql.util.PSQLException: The column name id1_15_0_ was not found in this ResultSet.

因为需要额外的参数来计算字段,所以确实不能使用@Formula,甚至不能使用getter来计算字段。 不幸的是,在您的情况下,我们想到的唯一一件事是,假设您正在为Hibernate使用基于EntityManager的配置,那么就是利用它的@PostLoad事件侦听器,您可以使用它在实体加载时计算字段值,如:

public class Question extends Entry {
    @PostLoad
    private void postLoad() {
        this.distance = DistanceCalculator.calculateDistance(Double param1,Double param2);       
        //other calculations
    }
}
当然,这只是一种变通方法,这意味着您必须在某个地方有一个静态方法来执行本机查询。
我建议您在需求中尽可能将“距离”概念从问题实体中分离出来,并在需要时使用本机SQL函数调用或服务方法进行计算。

从SQL查询中检索结果集时,我已经使用PostGIS函数调用按距离对列表进行排序。这意味着每个元素的距离已经从DB计算出来。我真的希望找到一种方法,不让我的Spring应用程序再次进行计算,而是直接从DB中获取值。在类似的情况下,我制作了一个信封,并将我的查询自定义映射到该信封(即,将您的距离字段与问题实体分开,并将它们包装在一个自定义实体类中,其中包含两个字段:一个问题和一个非暂时性“距离”字段)。之后,您可以使用SqlResultSetMapping将查询映射到该包装器。然后,您就可以单独保留问题实体。请参阅我的编辑。我正确理解你的建议了吗?你好@isADon,我也有同样的问题(改用MySQL)。你能找到解决办法吗?
Query query = entityManager.createNativeQuery("SELECT q.*, 222.22 as distance from question q", "MappingQ");
org.postgresql.util.PSQLException: The column name id1_15_0_ was not found in this ResultSet.
public class Question extends Entry {
    @PostLoad
    private void postLoad() {
        this.distance = DistanceCalculator.calculateDistance(Double param1,Double param2);       
        //other calculations
    }
}