Spring data rest managing all entities with one cr

2020-04-18 04:55发布

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.

2条回答
放我归山
2楼-- · 2020-04-18 05:23

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.

查看更多
We Are One
3楼-- · 2020-04-18 05:43

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

查看更多
登录 后发表回答