Spring data rest 使用一个 crud 存储库管理所有实体 [英] Spring data rest managing all entities with one crud repository

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

问题描述

我需要知道是否有可能在 Spring Data Rest 中使用一个 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.

我尝试插入,到目前为止运行良好.但是这种方法不支持其他操作.除了使用两个 crud 存储库来执行此操作之外,还有其他方法吗?

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 作者.

Code example of the Spring Data author.

我的示例.

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

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