I woke up this morning and wanted to verify the JPA OneToMany annotation. The data of the primary entity (One) and the secondary entity (Many) were all inserted into the database, but NULL was inserted into the foreign key ID of the extra side. After a query, there was a problem in use

Two entities

@Entity
@Table(name = "Book")
@Setter
@Getter
public class Book implements Serializable {

    @Id
    @Column(name = "BookId")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "BookName")
    private String bookName;

    @Column(name = "Isbn")
    private String isbn;
 
    // Here I maintain that a book can be handled by multiple publishers
    @OneToMany(mappedBy = "book", cascade = CascadeType.ALL,fetch = FetchType.EAGER)
    private List<Publisher> publisherList = new ArrayList<>();
}
Copy the code
@Entity
@Table(name = "Publisher")
@Setter
@Getter
public class Publisher implements Serializable {

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

    private String publisherName;

    public Publisher(a){}

    @ManyToOne
    @JoinColumn(name = "BookId")
    private Book book;
}
Copy the code

Client call

public static void main(String[] args) {
    ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);

    DataSource dataSource = context.getBean(DataSource.class);
    System.out.println("DataSource:"+dataSource.getClass().getName());


    Book book = new Book();
    book.setBookName("Java from entry to abandonment");
    book.setIsbn("1");

    Publisher publisher = new Publisher();
    publisher.setPublisherName("Tsinghua Press");
    // Set the book property here, otherwise the BookId foreign key of publisher table is NULL
    publisher.setBook(book);
    
    //这里要使用getPublisherList.add() 
    Book.setpublisherlist (...); // If an ArrayList is new, use book.setPublisherList(...). The data is not valid
    book.getPublisherList().add(publisher);

    BookRepository bookRepository = context.getBean(BookRepository.class);
    bookRepository.save(book);

}
Copy the code