我有一個無狀態的ejb bean,有一個entitymanager(em)和這個函數。在什麼情況下會發生這種奇怪的jpa行爲?
public void what(Long commentId) {
Comment c = em.find(Comment.class, commentId);
em.refresh(c);
CommentUpdate cu = new CommentUpdate(c, "new Text");
em.persist(cu);
c.getUpdates().add(0, cu);
int i = c.getUpdates().size();
em.flush();
int j = c.getUpdates().size();
if (i != j)
System.err.println("What?");
}
CommentUpdate是一個非常簡單的實體類。
@Entity
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class CommentUpdate extends AbstractEntity {
@ManyToOne
@Getter
@Setter
private Comment comment;
@Getter
@Setter
private String text;
public CommentUpdate(Comment comment, String text) {
this.comment = comment;
this.text = text;
}
}
評論是稍微複雜一些,但已經像這樣定義的關係:
@OneToMany(mappedBy = "comment")
@OrderBy("createdAt DESC")
@Getter
private List<CommentUpdate> updates = new ArrayList<>();
的事情是現在,有時「什麼?」被打印到日誌中。 刷新後新創建的CommentUpdate消失。但又回到了下一次刷新。 這是一個更大的vaadin項目中的方法,我還沒有能夠在一個小型/簡單的項目中重現這一點。有沒有這種情況,這是合乎邏輯的行爲,或者這可能是Glassfish(4.1.1)使用的eclipselink(2.6)中的錯誤?
謝謝您的回答啓用緩存。我在CommentUpdate類的cunstructor中設置關係的擁有方。現在我認爲它與一個@preUpdate方法和另一個與CascadeType.REFRESH的關係有關。如果我能瞭解更多,我會自己回答這個問題。 – raffael
然後,你應該首先設置關係的雙方,然後才調用'persist(cu)'。無論如何,張貼更多的上下文可以幫助 - CommentUpdate的代碼,任何'@ PreUpdate','@ PostPersist'等方法。 –