rest - 来自非实体对象的 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();
}
}
解决方案
在我的例子中,我们将实体设为不可变,如下所示。因此将数据库结果存储在金额对象中。
@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;
}
推荐阅读
- sympy - 用多项式替换矩阵时的问题
- reactjs - 在通过道具时无法读取未定义的属性“地图”
- react-native - 反应导航嵌套无路由参数 v5
- ios - SwiftUI Xcode 12.3 无法更改工具栏中的按钮大小
- html - 我可以动态地将我的 Firefox 书签添加到 html 文件/Custome 主页吗?
- python - 求解具有 3 个变量的方程
- javascript - 当窗口为 1300px 时,它没有检测到我的代码中的 top 属性
- angular - Idenity.Core GenerateEmailConfirmationTokenAsync 来自Angular 10 WebApp的无效令牌
- python - Python Tkinter 如何获取 Canvas 的图像?
- r - 无法在 R 中使用 ggplot2 调整对数曲线