首页 > 解决方案 > 基于实体名称及其主键的通用数据获取 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;
    }

标签: javaspring-bootjpa

解决方案


也许您应该尝试Spring Data REST。这是一种与您不同的方法,但它是一个 Spring 项目,受到积极支持,它允许您将存储库直接公开为 REST 端点。


推荐阅读