簡體   English   中英

通過Spring Boot API在REST調用中發布oneToMany

[英]POSTing oneToMany in a REST call via Spring Boot API

當我從單個REST調用POST以創建庫並為庫關聯Books時,我遇到了問題。 已創建庫記錄,但相關書籍不是。 圖書館和書籍有一種關系。 我的POST請求和響應如下 -

POST - http:// localhost:8080 / libraries /

REQUEST BODY
{
    "name":"My Library",
    "books": [
        {"title": "Effective Java", "isbn": "1234"},
        {"title": "Head First Java", "isbn": "5678"}
        ]
}
REPOSNSE 
1

POST后獲取庫 - http:// localhost:8080 / libraries /

[
    {
        "id": 1,
        "name": "My Library",
        "books": [],
        "address": null
    }
]

POST以創建庫並添加Books GET REQUEST for Libraries

楷模

package com.publiclibrary.domain;

import java.util.List;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;

import org.springframework.data.rest.core.annotation.RestResource;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@Entity
public class Library {

    @Id
    @GeneratedValue
    private long id;

    @Column
    private String name;

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

    @OneToOne
    @JoinColumn(name = "address_id")
    @RestResource(path = "libraryAddress", rel="address")
    private Address address;

    // standard constructor, getters, setters
    public Library(String name) {
        super();
        this.name = name;
    }

}
package com.publiclibrary.domain;

import java.util.List;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.validation.constraints.NotNull;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
//@Builder
//@AllArgsConstructor
@Entity
public class Book {

    @Id
    @GeneratedValue
    private long id;

    @NotNull
    private String title, isbn;

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


    @ManyToMany(mappedBy = "books")
    private List<Author> authors;
}

REPOSITORY

package com.publiclibrary.repo;

import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

import com.publiclibrary.domain.Book;

@RepositoryRestResource(path = "books", collectionResourceRel = "books")
public interface BookRepository extends PagingAndSortingRepository<Book, Long> {

}
package com.publiclibrary.repo;

import org.springframework.data.repository.CrudRepository;

import com.publiclibrary.domain.Library;

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

服務

package com.publiclibrary.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.publiclibrary.domain.Library;
import com.publiclibrary.repo.LibraryRepository;

@Service
public class LibraryService {

    @Autowired
    LibraryRepository libraryRepository;

    public List<Library> getAllLibrarys() {
        List<Library> librarys = new ArrayList<Library>();
        libraryRepository.findAll().forEach(library -> librarys.add(library));
        return librarys;
    }

    public Library getLibraryById(long id) {
        return libraryRepository.findById(id).get();
    }

    public void saveOrUpdate(Library library) {
        libraryRepository.save(library);
    }

    public void delete(long id) {
        libraryRepository.deleteById(id);
    }
}

RESTCONTROLLER

package com.publiclibrary.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.publiclibrary.domain.Library;
import com.publiclibrary.service.LibraryService;

@RestController
public class LibraryController {

    @Autowired
    LibraryService libraryService;

    @GetMapping("/libraries")
    private List<Library> getAllLibrarys() {
        return libraryService.getAllLibrarys();
    }

    @GetMapping("/libraries/{id}")
    private Library getLibrary(@PathVariable("id") int id) {
        return libraryService.getLibraryById(id);
    }

    @DeleteMapping("/libraries/{id}")
    private void deleteLibrary(@PathVariable("id") int id) {
        libraryService.delete(id);
    }

    @PostMapping("/libraries")
    private long saveLibrary(@RequestBody Library library) { 
        libraryService.saveOrUpdate(library);
        return library.getId(); 
    }

}

如何按照我的意圖創建圖書館並添加圖書? 感謝任何幫助!

嘗試在Library類中的books集合中添加cascade persist(或者更好的只是級聯all)。 例如

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

我按照這篇文章解決了這個問題。 我明確地處理了解析JSON並創建我的數據對象。 另外,我在parent(Library)類中添加了添加和刪除方法,並定義了equals和hashcode,原因在上面的鏈接中有解釋。

我的代碼更改如下 -

圖書館 -

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

public void addBook(Book book) {
    books.add(book);
    book.setLibrary(this);
}

public void removeBook(Book book) {
    books.remove(book);
    book.setLibrary(null);
}

書 -

@JsonIgnoreProperties("books")
private Library library;    

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof Book )) return false;
    return id != null && id.equals(((Book) o).id);
}
@Override
public int hashCode() {
    return 31;
}

LibraryController -

    @PostMapping("/libraries")
private long saveLibrary(@RequestBody Map<String, Object> payload) {
    Library library = new Library();
    library.setName(payload.get("name").toString());

    @SuppressWarnings("unchecked")
    List<Map<String, Object>> books = (List<Map<String, Object>>) payload.get("books");
    for (Map<String, Object> bookObj : books) {
        Book book = new Book();
        book.setTitle(bookObj.get("title").toString());
        book.setIsbn(bookObj.get("isbn").toString());
        library.addBook(book);
    }

    libraryService.saveOrUpdate(library);

    return library.getId(); 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM