【发布时间】:2017-04-13 00:38:36
【问题描述】:
在花了一天的大部分时间在这之后,我在 @ManyToOne 和 @OneToMany 映射中遗漏了一些明显的东西。
我有两个要通过 REST 公开的类,一个项目类和一个里程碑类。每个项目可以关联多个里程碑。
@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
}
我的存储库类是:
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);
}
使用 localhost:8080/projects/1/milestones 的帖子更新项目的 URI 不起作用,但是我可以在没有任何链接的情况下创建新项目和里程碑。
我的目标是发布项目条目,然后随着时间的推移发布里程碑条目,这将更新项目类中相关里程碑的列表。
知道可能出了什么问题吗?
更新:
我使用 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 列为空
【问题讨论】:
-
“不工作”包含零信息。
-
尽管里程碑和项目类之间有引用,但这两个实体没有链接。发布数据有效,但生成的 project_milestones 表和 project_id 列为空
-
为什么不在你实际做事的地方显示代码。
标签: java spring jpa spring-data spring-data-rest