Home > AI > Backend > SpringBoot > mysql-connector-java >

OneToMany-JpaRepository-save

Example

Book.java

@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "books")
public class Book {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String title;
    private String author;

    @Column(unique = true)
    private String isbn;

    @OneToMany(mappedBy = "book", fetch = FetchType.LAZY,
            cascade = CascadeType.ALL)
    private Set<BookPage> pages;



    public Book(String title, String author, String isbn) {
        this.title = title;
        this.author = author;
        this.isbn = isbn;
    }

}

BookPage.java (Don’t name Page, JPA has Page class, will have error)

@Data
@NoArgsConstructor
@Entity
@Table(name = "book_pages")
public class BookPage {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private int number;
    private String content;
    private String chapter;

    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "book_id", nullable = false)
    private Book book;


    public BookPage(int number, String content, String chapter, Book book) {
        this.number = number;
        this.content = content;
        this.chapter = chapter;
        this.book = book;
    }

}

BookRepository.java

@Repository
public interface BookRepository extends JpaRepository<Book, Long> {

    Book findByIsbn(String isbn);
}

BookPageRepository.java

public interface BookPageRepository extends JpaRepository<BookPage, Long> {

    List<BookPage> findByBook(Book book, Sort sort);
}

TestRepository.java

@Slf4j
@SpringBootTest
public class TestRepository {





    @Autowired
    BookRepository bookRepository;
    @Autowired
    BookPageRepository pageRepository;
    @Test
    public void test1() {
        // create a new book
        Book book = new Book("Java 101", "John Doe", "123456");

        // save the book
        bookRepository.save(book);

        // create and save new pages
        pageRepository.save(new BookPage(1, "Introduction contents", "Introduction", book));
        pageRepository.save(new BookPage(65, "Java 8 contents", "Java 8", book));
        pageRepository.save(new BookPage(95, "Concurrency contents", "Concurrency", book));
    }
}

Leave a Reply