如何在Spring Data Rest应用程序中创建实体之间的引用 [英] How to create a reference between entities in Spring Data Rest Application

查看:345
本文介绍了如何在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,
  • 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.

这篇关于如何在Spring Data Rest应用程序中创建实体之间的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆