如何在Spring Data Rest应用程序中创建实体之间的引用
我正在尝试使用Spring Boot + Data Rest + JPA构建简单的应用程序。
A具有一对多关系的Category和Book实体:
I'm trying to build simple application with Spring Boot + Data Rest + JPA.
A have Category and Book entities with one to many relationship:
<!-- language-all: java -->
@Entity
public class Category {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "category")
private Set<Book> books;
...getters & setters next...
}
和
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
@ManyToOne
private Category category;
...getters & setters next...
}
每个实体的简单存储库
@RepositoryRestResource
public interface BookRepository extends JpaRepository<Book, Long> {}
@RepositoryRestResource
public interface CategoryRepository extends JpaRepository<Category, Long> {}
申请:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
应用程序启动成功,我可以创建书籍和类别。
问:如何创建和删除它们之间的引用?
Application starts successfully and I can create books and categories.
Q.: How I can create and remove a references between them?
我尝试了此处描述的解决方案: 在Spring Data REST中发布@OneToMany子资源关联
- 对我不起作用:在带有ContentType:text / uri-list标题的PUT请求中,我有响应代码204,数据库中没有变化。仔细观察我在日志中发现了以下调试消息:
I tried solution described here: POSTing a @OneToMany sub-resource association in Spring Data REST - didn't work for me: on PUT request with "ContentType: text/uri-list" header I have response code 204 and no changes in the database. Looking deeper I was found the following debug message in the log:
s.w.s.m.m.a.RequestMappingHandlerMapping :
Did not find handler method for [/categories/1/books]
此网址仅适用于GET请求。
This url is available only for GET requests.
问:我的配置有什么问题?
Q.: Any ideas what is wrong in my configuration?
谢谢。
要创建 book(id:1)和category(id:1)之间的关系:
To create a relation between book(id:1) and category(id:1):
- put request,
- 媒体类型:text / uri-list,
- 数据: http:// localhost:8080 / categories / 1
- 请求 http:// localhost:8080 / books / 1 / category
- put request,
- media type: text/uri-list,
- data: http://localhost:8080/categories/1
- request to http://localhost:8080/books/1/category
卷曲示例:
curl -X PUT -H "Content-Type: text/uri-list" -d "http://localhost:8080/categories/1" http://localhost:8080/books/1/category
To 删除此关系只是对同一地址执行删除请求
To remove this relation just do a delete request to the same address
curl示例:
curl -X DELETE http://localhost:8080/books/1/category
并回答你的第二个问题:你的配置看起来不错,我在你的代码上测试了这个例子。
And to answer your 2nd question as well: your configuration looks good and I have tested this example on your code.