Toseef Zafar
Toseef Zafar

Reputation: 1767

JPA - mapping additional calculated value from an entity

I have an entity called Taxi which has got its location information saved in it. I have a stored procedure which returns this entity fields and an additional field called 'distance' which is calculated by the stored procedure. The question is I am returning Taxi entity from the stored procedure which obviously doesn't have the distance field, how do I get this calculated distance field?

This is how it looks:

List<Taxi> getTaxisAroundMe(Integer customerId,Integer distance); 

Upvotes: 2

Views: 196

Answers (1)

xerx593
xerx593

Reputation: 13261

Introduce:

 @Entity
 @Immutable
 public class TaxiReadOnly extends Taxi {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id", updatable = false, nullable = false)
    private Long /*?*/ id;

    private Integer distance;
    //get+set
 }

Then:

public interface TaxiReadOnlyRepository {
   List<TaxiReadOnly> calcDistance(/*input params*/);
}


// as before
public interface TaxiRepository extends CrudRepository<Taxi, Long>,
  //but now with
  TaxiReadOnlyRepository {}


// and
public class TaxiReadOnlyRepositoryImpl implements TaxiReadOnlyRepository {
   @PersistenceContext
   private EntityManager em;
   @Override
   public List<TaxiReadOnly> calcDistance(/*input params*/) {
       return em.createNativeQuery("BEGIN call_ur_procedure(:inParam1, ...); END;")
      //.setParameter("inParam1", inParam1)
      .getResultList();
  }
}

see:

Upvotes: 1

Related Questions