Spring 通过 REST 的 JPA

Spring JPA via REST

在花费了一天的大部分时间之后,我遗漏了一些关于@ManyToOne 和@OneToMany 映射的明显信息。

我有两个 class 想要通过 REST 公开,一个项目 class 和一个里程碑 Class。每个项目都可以关联多个里程碑。

    @Entity
    public class Project {

        @Id
        @Column(name="project_id")
        @GeneratedValue(strategy = GenerationType.AUTO)
        private long id;

        @OneToMany   
        private List<Milestone> milestones = new ArrayList<>();

        private String name;
        private String description;

        // Getter and setters removed for brevity
        }

    @Entity
    public class Milestone {    

        @Id
        @Column(name="milestone_id")
        @GeneratedValue(strategy = GenerationType.AUTO)    
        private long id;

        private String name;
        private String description;           

        @ManyToOne
        @JoinColumn(name="project_id")
        private Project project;

       // Getter and setters removed for brevity
}

我的存储库class是:

public interface ProjectRepository extends JpaRepository<Project, Long> {
    List<Project> findByName(@Param("name") String name);       
}

public interface MilestoneRepository extends JpaRepository<Milestone, Long> {
    List<Milestone> findByName(@Param("name") String name);        
}

将带有 post 的项目的 URI 更新为 localhost:8080/projects/1/milestones 不起作用,但是我可以在没有任何链接的情况下创建新项目和里程碑。

我的目标是 post 项目条目,然后随着时间的推移 post 里程碑条目,这将更新项目的相关里程碑列表 class。

知道哪里出了问题吗?

更新:

使用 Python 的 HTTPIE 实用程序,我执行了以下操作来创建初始项目:

http post localhost:8080/projects name="test" description="test"

然后我执行以下操作来分配一个里程碑:

http post localhost:8080/milestones name="test" description="test" project="http://localhost:8080/projects/1"

返回的响应是:

HTTP/1.1 201
Content-Type: application/json
Location: http://localhost:8080/milestones/1
Transfer-Encoding: chunked
{
  "_links": {
     "milestone": {
       "href": "http://localhost:8080/milestones/1"
      },
     "project": {
       "href":"http://localhost:8080/milestones/1/project"
      },
      "self":{
        "href":"http://localhost:8080/milestones/1"
      }
     },
      "description":"test",
      "name":"test"
     }

在数据库中,PROJECT_ID 列为空

你需要POST到

http://localhost:8080/milestones

其中通过其资源 URL:

向关联项目包含一个 link
{
    "name": "milestone name",
    "description": "milstone description",
    "project": "http://localhost:8080/projects/1"
}