java - 基于实体名称及其主键的通用数据获取 API
问题描述
我正在开发一个通用 API 来根据实体名称及其主键获取数据。用于获取映射的 URL:api/fetch/{id}/data/{entity}
存在许多实体,例如学生、课程、讲师、班级……根据实体名称,API 应通过 URL 中的给定 id 返回该实体的数据。使用 Spring Boot 和 JPA 的最佳方法应该是什么?在下面尝试,但当实体数量众多且不断增加时无法工作。需要一个通用的方法。
@RestController
public class Datacontroller{
@Autowired
CourseRepo courserepo;
@Autowired
Studentrepo studentrepo;
@GetMapping("api/fetch/{id}/data/{entity}")
public <T> T getData(@PathVariable("id") String id, @PathVariable("entity") String entity) {
T l = null;
//depending on entity
if("course".equals(entity)) {
Optional<Course> c = courserepo.findById(id);
l=(T) c.get();
}
if("student".equals(entity)) {
Optional<Student> a = studentrepo.findById(id);
l = (T) a.get();
}
return l;
}
解决方案
也许您应该尝试Spring Data REST。这是一种与您不同的方法,但它是一个 Spring 项目,受到积极支持,它允许您将存储库直接公开为 REST 端点。
推荐阅读
- python - 请求失败,状态码为 401,仅适用于 IOS 上的 React Native Expo,但在其他任何地方都可以使用
- python - discord.py 的颜色代码
- python - Pandas concat 不断添加新的索引列
- testing - 在没有 Vue CLI 的情况下测试纯 javascript Vue 组件
- flutter - 使用不同的应用程序 ID 构建不同风格的 Flutter 应用程序
- c++ - UB从免费存储中删除提供存储的字符数组时?
- javascript - KnockoutJS - 使 NESTED JSON 字段可观察/可编辑
- tree - 计算树中节点的所有值(在 L 和 R 之间)之和的程序中的逻辑错误
- math - 2D 中 2 条线之间的相似性
- java - RecursiveLinkedCollection 和删除方法 java