Hi,
I'm not sure if this is a bug or correct behaviour. Imho it is wrong but I thought i ask here before filing a bug report.
Explanation:
Two entities Book and Page
@Entity
public class Book extends AbstractSimpleEntity implements Serializable {
private static final long serialVersionUID = 1L;
@OneToMany(mappedBy = "book", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
@OrderColumn(name = "position")
@Getter
@Setter
protected List<Page> pages = new ArrayList<>();
}
@Entity
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class Page extends AbstractSimpleEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Getter
@ManyToOne
protected Book book;
@Getter
@Setter
private boolean done = false;
public Page(Book book) {
this.book = book;
}
}
And this function where the result is not what i expected
private static void editFirstBookPage(Long bookId) {
EntityManager em = EmfHandler.getEM();
try {
em.getTransaction().begin();
Book book = em.find(Book.class, bookId);
em.detach(book);
List<Page> pages = new ArrayList<>(book.getPages());
// Uncomment this to workaround the problem
// for (Page page : pages) {
// em.detach(page);
// }
pages.get(0).setDone(true);
Book origBook = em.find(Book.class, bookId);
em.refresh(origBook);
origBook.setPages(pages); // thats where done flag is reseted
// book = em.merge(book); //Same Problem with merge
em.flush();
em.getTransaction().commit();
LOG.info("Updated Pages");
} finally {
if (em.getTransaction().isActive())
em.getTransaction().rollback();
EmfHandler.disposeEM(em);
}
}
Right after detaching the book entity I access the pages relation and because CascadeType.DETACH (CascadeType.ALL) I assumed, that the pages are also detached, but they are not. So setting pages on origBook refreshes the pages too because it is also CascadeType.REFRESH and so my done flag set back to false.
I can provide a maven project demonstrating this if someone is wants to test it.
What do you think? Is this a bug or correct behaviour?
Thanks
Raffael