JPA双向级联更新(不推荐)

注解多对一
@ManyToOne(fetch = FetchType.LAZY,cascade = CascadeType.ALL)
@JoinColumn(name = "type_id")//关联字段
private BookType bookTypeByTypeId;//多对一

注解一对多
@OneToMany(fetch = FetchType.EAGER,cascade = CascadeType.ALL)
@JoinColumn(name = "type_id")
private Collection bookInfosByTypeId=new HashSet();

(没有单独的inverse属性(Hiberante的ORM映射文件中有),这里mappedBy和JoinColumn不共融)

表设置级联更新:

image.png

添加图书的时候添加分类


注意 :
persist方法必须是新添加的分类,不是已经有的分类。

public void addBook(){
EntityManager entityManager = JPAUitls.createSession();
EntityTransaction transaction = entityManager.getTransaction();
transaction.begin();
BookInfo bookInfo = new BookInfo();
bookInfo.setBookName("Java");
bookInfo.setBookAuthor("1803");
bookInfo.setBookDate(new Date().getTime());
bookInfo.setBookDesc("java1803");
bookInfo.setBookPrice(8.3);
bookInfo.setBookPublish("清华");
BookType bookType = new BookType();
//新分类,DB没记录,这种方式不可以调用BookTypeDao获取已有的分类。
bookType.setTypeName("test");
bookType.setTypeDesc("test");
bookInfo.setBookTypeByTypeId(bookType);
entityManager.persist(bookInfo);
transaction.commit();
entityManager.close();
}
或者使用merge方法,可以是已有的分类。

添加分类的时候添加图书
public void addType(){
EntityManager entityManager = JPAUitls.createSession();
EntityTransaction transaction = entityManager.getTransaction();
transaction.begin();
BookType bookType = new BookType();
bookType.setTypeName("Java1803222");
bookType.setTypeDesc("Java1803所有工程师快毕业了");
BookInfo bookInfo = new BookInfo();//新添加图书
bookInfo.setBookName("Java222");
bookInfo.setBookAuthor("1803");
bookInfo.setBookDate(new Date().getTime());
bookInfo.setBookDesc("java1803");
bookInfo.setBookPrice(8.3);
bookInfo.setBookPublish("清华");
bookType.getBookInfosByTypeId().add(bookInfo);
entityManager.persist(bookType);
transaction.commit();
entityManager.close();
}

你可能感兴趣的:(JPA双向级联更新(不推荐))