今早起床后想验证一下jpa OneToMany注解。 写了demo, 主实体,也就是One对应的一方和从实体,也就是Many对应的实体数据都插入数据库了,但是在多的一方外键id插入NULL, 查询了一下,是使用上的问题
两个实体
@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;
//这里我维护了一本书可以由多个出版商负责
@OneToMany(mappedBy = "book", cascade = CascadeType.ALL,fetch = FetchType.EAGER)
private List<Publisher> publisherList = new ArrayList<>();
}
复制代码
@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(){}
@ManyToOne
@JoinColumn(name = "BookId")
private Book book;
}
复制代码
客户端调用
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从入门到放弃");
book.setIsbn("1");
Publisher publisher = new Publisher();
publisher.setPublisherName("清华出版社");
//这里要设置book属性, 否则publisher表BookId外键是NULL
publisher.setBook(book);
//这里要使用getPublisherList.add()
//如果上面先new一个ArrayList, 在这里用book.setPublisherList(...) 数据也不生效
book.getPublisherList().add(publisher);
BookRepository bookRepository = context.getBean(BookRepository.class);
bookRepository.save(book);
}
复制代码
近期评论