【发布时间】:2011-06-01 23:24:39
【问题描述】:
我需要一点时间来解释这一点,所以请和我在一起。我有表 NewsFeed 与自身具有 OneToMany 关系。
@Entity
public class NewsFeed(){
...
@ManyToOne(optional=true, fetch=FetchType.LAZY)
@JoinColumn(name="REPLYTO_ID")
private NewsFeed replyTo;
@OneToMany(mappedBy="replyTo", cascade=CascadeType.ALL)
private List<NewsFeed> replies = new ArrayList<NewsFeed>();
public void addReply(NewsFeed reply){
replies.add(reply);
reply.setReplyTo(this);
}
public void removeReply(NewsFeed reply){
replies.remove(reply);
}
}
所以你可以这样想。每个提要都可以有一个List 的回复,这些回复也是NewsFeed 类型。现在我很容易删除原始提要并取回更新的列表。删除后我需要做的就是这个。
feeds = scholarEJB.findAllFeed(); //This will query the db and return updated list
但我在尝试删除 replies 并取回更新后的列表时遇到问题。所以这就是我删除replies 的方法。在我的 JSF 托管 bean 中,我有
//Before invoke this method, I have the value of originalFeed, and deletedFeed set.
//These original feeds are display inside a p:dataTable X, and the replies are
//displayed inside p:dataTable Y which is inside X. So when I click the delete button
//I know which feed I want to delete, and if it is the replies, I will know
//which one is its original post
public void deleteFeed(){
if(this.deletedFeed != null){
scholarEJB.deleteFeeds(this.deletedFeed);
if(this.originalFeed != null){
//Since the originalFeed is not null, this is the `replies`
//that I want to delete
scholarEJB.removeReply(this.originalFeed, this.deletedFeed);
}
feeds = scholarEJB.findAllFeed();
}
}
然后在我的 EJB 学者EJB 里面,我有
public void removeReply(NewsFeed feed, NewsFeed reply){
feed = em.merge(feed);
comment.removeReply(reply);
em.persist(comment);
}
public void deleteFeeds(NewsFeed e){
e = em.find(NewsFeed.class, e.getId());
em.remove(e);
em.getEntityManagerFactory().getCache().evict(NewsFeed.class); //Like fdreger suggested
}
当我离开时,实体(回复)会从数据库中正确删除,但在 feeds 列表中,reply 的引用仍然存在。直到我注销并重新登录,回复才会消失。
【问题讨论】: