Spring Data Rest通过一个Crud存储库管理所有实体 [英] Spring data rest managing all entities with one crud repository

查看:53
本文介绍了Spring Data Rest通过一个Crud存储库管理所有实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要知道是否有可能通过spring数据仓库中的一个crud存储库来管理多个实体.

I need to know is there any possibility to manage several entities with one crud repository in spring data rest.

示例:

图书馆实体

@Entity
public class Library {

    @Id
    @GeneratedValue
    private long id;

    @Column
    private String name;

    @OneToMany(mappedBy = "library")
    private List<Book> books;
}

图书实体

@Entity
public class Book {

    @Id
    @GeneratedValue
    private long id;

    @Column(nullable=false)
    private String title;

    @ManyToOne
    @JoinColumn(name="library_id")
    private Library library;

}

我的要求是

public interface LibraryRepository extends CrudRepository<Library, Long> { }

只能使用此存储库来管理图书馆和图书实体.

is to have only this repository to manage both library and the book entities.

我尝试插入,到目前为止效果很好.但是此方法不支持其他操作.除了拥有两个原始存储库之外,还有什么其他方法.

I tried inserting and it is working well so far. but other operations are not supported by this approach. is there any other approach rather than having two crud repositories to do this.

推荐答案

当然可以.只需像这样更正您的资料库:

Of course you can. Just correct a little your Library like this:

@OneToMany(mappedBy = "library", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Book> books;

然后,您可以使用以下有效负载创建/更新您的图书馆及其书籍:

Then you can create/update your Library and its books with this payload:

{
    "name": "library1",
    "books": [
        {
            "title": "book1"
        },
        {
            "title": "book2"
        }
    ]
}

代码我的示例.

这篇关于Spring Data Rest通过一个Crud存储库管理所有实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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