title: Spring entity dynamically calculated field with parameter from native query
body: <p>I have a somewhat complex entity like following (Notice the super-class with many more fields):</p>
  
  <pre><code>public class Question extends Entry {
  
      @OneToMany(orphanRemoval = true, mappedBy = "question")
      @JsonManagedReference
      private List&lt;Answer&gt; answers = new ArrayList&lt;&gt;();
  
      private Long viewCount = 0L;
  
      private Category category;
  
      @OneToMany(mappedBy = "question", fetch = FetchType.LAZY,
              cascade = CascadeType.ALL, orphanRemoval = true)
      private List&lt;QuestionTranslation&gt; translations = new ArrayList&lt;&gt;();
  
      @Transient
      private double distance;
  }
  </code></pre>
  
  <p><code>distance</code> should be calculated from the DB when retrieving the result set from a native query.
  E.g.</p>
  
  <pre><code>SELECT q.*, ST_Distance_Sphere(cast(q.location as geometry), ST_MakePoint(cast(?1 as double precision), cast(?2 as double precision))) as distance from question q
  </code></pre>
  
  <p>I cannot use <code>@Formula</code> to annotate my field <code>distance</code> since the query has to take parameters.</p>
  
  <p>How can I map the field <code>distance</code> from the SQL query result to my entity field <code>distance</code> while leaving all the other mappings to be done by Hibernate?</p>
  
  <h3>Edit</h3>
  
  <p>Based on @gmotux suggestion I created a wrapper entity.</p>
  
  <pre><code>@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;
  }
  </code></pre>
  
  <p>Query</p>
  
  <pre><code>Query query = entityManager.createNativeQuery("SELECT q.*, 222.22 as distance from question q", "MappingQ");
  </code></pre>
  
  <p>But it always fails with </p>
  
  <pre><code>org.postgresql.util.PSQLException: The column name id1_15_0_ was not found in this ResultSet.
  </code></pre>