来自非实体对象的REST端点

时间:2019-09-11 14:09:28

标签: rest spring-boot

Spring的新手-我想拥有一个REST端点,该端点公开SQL查询的结果。 Amount类不是@Entity,而是另一个表中的某些字段。我可以将其声明为@Entity,但是Spring Data会为Amount创建一个我不想要的表。但是,如果没有@Entity,Spring将会抱怨:

java.lang.IllegalArgumentException: Not a managed type: interface com.swed.fuelcounter.entities.Amount

下面的代码对我来说很好用,但是我不需要数量实体,如果没有它怎么办?

服务类别:

@RestController
@RequestMapping(value = "/rest")
class AmountsService {
    private final AmountRepository repository;

    public AmountsService(AmountRepository repository) {
        this.repository = repository;
    }



    @RequestMapping(value = "/{id}/amount-by-month", method = RequestMethod.GET)
    public ResponseEntity<List<AmountInterface>> getAmountByMonth(@PathVariable("id") int id) {
        List<Amount> amounts = repository.sumAmountByDateAndDriver(id);
        return new ResponseEntity<>(amounts, HttpStatus.OK);
    }
}

POJO类的数量:

public class Amount {

    public Amount(double amount, Date date){
        this.amount = amount;
        this.date = date;
    }


    @Getter
    @Setter
    private double amount;

    @Getter
    @Setter
    private Date date;
}

存储库接口和RepositoryImpl类:

public interface AmountRepository extends JpaRepository<Amount, Long> {

    List<Amount> sumAmountByDateAndDriver(int id);
}

@Component
public class AmountRepositoryImpl {

    @PersistenceContext
    private EntityManager entityManager;

    @Autowired
    private AmountRepository repository;

    @SuppressWarnings("unused")
    public List<Amount> sumAmountByDateAndDriver(int id) {
        String hql = "SELECT NEW Amount(Sum(price*volume) as amount, date) FROM record WHERE id = :id GROUP BY date";
        TypedQuery<Amount> query = entityManager.createQuery(hql, Amount.class);
        query.setParameter("id", id);
        return query.getResultList();
    }

}

1 个答案:

答案 0 :(得分:0)

在我的情况下,我们将实体设为不可变,如下所示。因此,将数据库结果存储在金额对象中。

@Entity
@Immutable
@Getter
public class Amount {

   public Amount(double amount, Date date){
      this.amount = amount;
      this.date = date;
   }

   /* The No-Args Constructor is needed for Hibernate */
   public Amount() { }

   @Column
   private double amount;

   @Column
   private Date date;
}