簡體   English   中英

如何在一對多關系中處理 Thymeleaf 和 Spring 中的 forms?

[英]How to handle forms in Thymeleaf and Spring in one to many relationships?

這些是下面的模型。 我省略了模型的 getter 和 setter。

預訂 class

@Entity
public class Book extends BaseEntity {

private String bookName;
private String bookSubtitle;
private String seriesName;
private String isbnNumber;
private String bookDescription;

@ManyToOne
private Author author;

@ManyToOne
private Publisher publisher;

///// Author class
@Entity
public class Author extends BaseEntity {
     private String authorName;
     private String authorDescription;

     @OneToMany(cascade = CascadeType.ALL, mappedBy = "author", fetch = FetchType.LAZY)
     private Set<Book> books = new HashSet<>(); 

///// 發布者 class

@Entity
public class Publisher extends BaseEntity {

private String publisherName;
private String publisherDescription;

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

protected Publisher() {}

public Publisher(String publisherName, String publisherDescription) {
    this.publisherName = publisherName;
    this.publisherDescription = publisherDescription;
}

// 我的家.html 文件。

 <form action="#" th:action="@{/api/v1/books}" th:object="${book}" th:method="POST">
            <div class="form-group col-7">
                <label for="bookName" class="col-form-label">Kitap Adi:</label>
                <input th:field="*{bookName}" type="text" class="form-control" id="bookName">
            </div>
            <div class="form-group col-7">
                <label for="subTitle" class="col-form-label">Alt Baslik:</label>
                <input th:field="*{bookSubtitle}" type="text" class="form-control" id="subTitle">
            </div>
            <div class="form-group col-7">
                <label for="seriesName" class="col-form-label">Seri Adi:</label>
                <input th:field="*{seriesName}" type="text" class="form-control" id="seriesName">
            </div>
            <div class="form-group col-7">
                <label for="isbnNumber" class="col-form-label">ISBN:</label>
                <input th:field="*{isbnNumber}" type="text" class="form-control" id="isbnNumber">
            </div>
            <div class="form-group">
                <label for="bookDescription" class="col-form-label">Kitap Aciklamasi:</label>
                <input th:field="*{bookDescription}" type="text" class="form-control" id="bookDescription">
            </div>

            <div class="form-group">
                <label for="exampleFormControlSelect1">Yazar sec</label>
                <select class="form-control" id="exampleFormControlSelect1" th:field="*{author}">
                    <option th:each="aut : ${authors}" th:value="${(aut.getAuthorName())}" th:text="${aut.getAuthorName()}"></option>
                </select>
            </div>

            <div class="form-group">
                <label for="exampleFormControlSelect2">Yayinci sec</label>
                <select class="form-control" id="exampleFormControlSelect2" th:field="*{publisher}">
                    <option th:each="publish : ${publishers}" th:value="${publish.getPublisherName()}" th:text="${publish.getPublisherName()}"></option>
                </select>
            </div>

            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Iptal</button>
                <button type="submit" class="btn btn-primary">Ekle</button>
            </div>
        </form>

這是我的 controller 的帖子,創建書。

@PostMapping("/books")
public Book createBook(Book book) {
    logger.info(book.toString());
    return bookService.save(book);
}

這是我的 bookService save() 方法,可以完成所有工作。 我已經從 Author 和 Publisher 創建了一個 object,並以循環瀏覽它們的形式。 所以,基本上我的目標是讓用戶選擇的作者和出版商名稱以及書籍詳細信息和 map 一起獲得。 但是,我嘗試了很多事情並進行了更改,並且還檢查了互聯網仍然無法提出解決方案。 這些代碼段有什么問題?

public Book save(Book book) {

    Set<Book> books = new HashSet<>();
    System.out.println(book.getPublisher().getPublisherName());
    System.out.println(book.getAuthor().getAuthorName());

    String authorName = book.getPublisher().getPublisherName();
    String publisherName = book.getAuthor().getAuthorName();
    
    Author author = authorRepository.findAuthorByAuthorName(authorName);
    Publisher publisher = publisherRepository.findByPublisherName(publisherName);

    book.setAuthor(author);
    book.setPublisher(publisher);

    books.add(book);
    
    author.setBooks(books);
    publisher.setBooks(books);

    return bookRepository.save(book);

}

最好創建一個專用的“表單數據”object。 在您的示例中,我會這樣做:

public class CreateBookFormData {
  private String bookName;
  private String bookSubtitle;
  private String seriesName;
  private String isbnNumber;
  private String bookDescription;

  private UUID authorId; // Use whatever type of primary key you are using here
  private UUID publisherId;
}

controller 將更改為:

@PostMapping("/books")
public Book createBook(CreateBookFormData formData) {
    logger.info(book.toString());
    // You can either pass in the `CreateBookFormData`, or convert it here to a `Book` instance.
    // You will need to convert the `authorId` and `publisherId` to the corresponding entities using their respective repositories or services
    return bookService.save(formData);
}

請注意,您不能使用作者或出版商的姓名,因為可能存在重復。 您需要使用實體的主鍵。

在您的 Thymeleaf 模板中,執行以下操作:

<select th:field="*{authorId}">
  <option th:each="author : ${authors}" th:text="${author.authorName}" th:value="${author.id}">
          </select>

並為發布者做同樣的事情。

暫無
暫無

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

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