我的数据库中有三元关系:User,Book和BookOrder。 JPA实体的定义如下:
class Book {
@Id
@Column(name = "ID")
private Integer id;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "book")
private Collection<BookOrder> bookOrderCollection;
....
}
class User {
@Id
@Column(name = "ID")
private Integer id;
@OneToMany(mappedBy = "reader")
private Collection<BookOrder> bookOrderCollection;
....
}
class BookOrder {
@JoinColumn(name = "BOOK_ID", referencedColumnName = "ID")
@ManyToOne
private Book book;
@PrimaryKeyJoinColumn(name = "READER_ID", referencedColumnName = "ID")
@ManyToOne
private User reader;
....
}
当我想要保存时,我就是这样做的:
Book book = ...;
User reader = ...;
BookOrder order = new BookOrder();
order.setBook(book);
order.setReader(reader);
book.getBookOrderCollection().add(order);
reader.getBookOrderCollection().add(order);
book.setQuantity(book.getQuantity() - 1);
bookFacade.edit(book);
BookFacade课程是:
class BookFacade {
public void create(Book entity) {
getEntityManager().persist(entity);
getEntityManager().flush();
}
public void edit(Book entity) {
getEntityManager().merge(entity);
}
public void remove(Book entity) {
getEntityManager().remove(getEntityManager().merge(entity));
}
public Book find(Object id) {
return getEntityManager().find(Book.class, id);
}
}
这样可以正常工作,因为数据库中的图书数量已更新,并且插入了BookOrder
。但是,在重新启动服务器(当我从数据库中拔出读卡器)之前,User
&#39; bookOrderCollection
不会更新。
我想避免执行usersFacade.edit(reader)
,因为为一个操作创建两个事务是不安全的。相反,我将cascade = Cascade.ALL
添加到reader
课程中的Order
字段,但它没有解决问题。
如何在一次交易中使其发挥作用?
答案 0 :(得分:2)
@OneToMany(cascade = CascadeType.ALL, mappedBy = "book")
是反向关系,而不是直接关系。将CASCADE
添加到关系的另一方(@ManyToOne
)可能会产生不同的效果。