首页 > 解决方案 > 来自非实体对象的 REST 端点

问题描述

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

Repository 接口和 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();
    }

}

标签: restspring-boot

解决方案


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

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

推荐阅读