Spring data rest managing all entities with one crud repository

本秂侑毒 提交于 2019-12-02 15:18:05

问题


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

Example :

Library entity

@Entity
public class Library {

    @Id
    @GeneratedValue
    private long id;

    @Column
    private String name;

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

Book entity

@Entity
public class Book {

    @Id
    @GeneratedValue
    private long id;

    @Column(nullable=false)
    private String title;

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

}

My requirement is

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.


回答1:


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"
        }
    ]
}

Code example of the Spring Data author.

My example.




回答2:


You cannot do that simply, since a bean will be created for each repository and this bean should be instantiated with entity type defined



来源:https://stackoverflow.com/questions/47198175/spring-data-rest-managing-all-entities-with-one-crud-repository

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!