JPA-映射实体的其他计算值

时间:2019-01-23 21:03:56

标签: hibernate spring-boot jpa orm spring-data-jpa

我有一个名为Taxi的实体,该实体中已保存其位置信息。我有一个存储过程,该存储过程返回该实体字段和一个由存储过程计算的称为“距离”的附加字段。问题是我要从显然没有距离字段的存储过程中返回出租车实体,如何获取此计算出的距离字段?

外观如下:

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

1 个答案:

答案 0 :(得分:1)

介绍:

 @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
 }

然后:

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();
  }
}

请参阅: