我正在开发一个通用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端点。