如何使用当前上下文JPA、JSF和Java集合删除项集合
我想删除与当前电影不匹配的评论 信息如何使用当前上下文JPA、JSF和Java集合删除项集合,java,jsf,jpa,collections,Java,Jsf,Jpa,Collections,我想删除与当前电影不匹配的评论 信息 jpaController=(CommentFacade)facesContext.getApplication().getELResolver().getValue(facesContext.getELContext(),null,“commentJpa”); movieController=(movieController)facesContext.getApplication().evaluateExpressionGet(facesContext,“
jpaController=(CommentFacade)facesContext.getApplication().getELResolver().getValue(facesContext.getELContext(),null,“commentJpa”);
movieController=(movieController)facesContext.getApplication().evaluateExpressionGet(facesContext,“{movie}”,movieController.class);
私有列表userCommentItems=null;
私有注释userComment=null;
公共列表getUserCommentItems(){
if(userCommentItems==null){
getUserPaginInfo();
Vector comments=(Vector)jpaController.findAll();
向量v=新向量(注释);
for(Iterator Iterator=comments.listIterator();Iterator.hasNext();){
userComments=(Comment)迭代器.next();
if(userComments.getMovie().getIdMovie()!=movieController.getMovie().getIdMovie()){
v、 删除(用户评论);
}
}
userCommntItems=v;
}
归还物品;
}
首先,这是一个糟糕的代码。这个版本怎么样
public List<Comment> getUserCommentItems() {
if (userCommentItems == null) {
getUserPagingInfo();
List<Comment> comments = jpaController.findAll();
for (Iterator<Comment> iterator = comments.iterator(); iterator.hasNext();){
userComments = iterator.next();
if (!userComments.getMovie().equals(movieController.getMovie()){
iterator.remove();
}
}
userCommntItems = comments;
}
return userCommentItems ;
}
public List getUserCommentItems(){
if(userCommentItems==null){
getUserPaginInfo();
List comments=jpaController.findAll();
for(Iterator Iterator=comments.Iterator();Iterator.hasNext();){
userComments=iterator.next();
如果(!userComments.getMovie().equals(movieController.getMovie()){
iterator.remove();
}
}
userCommntItems=注释;
}
归还物品;
}
改进:
- 不再使用不推荐的Vector类(尤其是不再使用不必要的强制转换)
- 使用
比较对象,而不是equals()
(您应该相应地实现=
)Movie.equals(对象)
- 无需复制集合,只需处理原始集合(如果您的DAO返回了我无法更改的内容,那么它就糟透了)
但要真正解决你的问题:
您是否正在为不同的电影重复使用此组件?如果是,将评论保留在字段中是毫无意义的。删除对
userCommentItems
的所有分配和读取,无错误但为空我得到一个空的数据表不抱歉,我现在得到所有评论,所有电影的所有评论。我的意思是,一旦评论出现,它们将保持不变我导航到的电影。对getIdMovie()的调用返回什么?类java.util.iterator中的metod remove无法应用于所需的给定类型:未找到参数:myBeans@Ignacio对不起,我的错,它不带参数。它删除了迭代中的当前元素(现在已修复代码)这是唯一的分配和读取userCommentItems@Ignacio您没有显示任何将数据写入数据库的代码,您只是在筛选数据。鉴于您显示的代码,我们无法知道数据如何在您的数据库中结束。它不是将数据写入数据库,而是使用userCommentIte的getter和setter将数据写入屏幕太太
public List<Comment> getUserCommentItems() {
if (userCommentItems == null) {
getUserPagingInfo();
List<Comment> comments = jpaController.findAll();
for (Iterator<Comment> iterator = comments.iterator(); iterator.hasNext();){
userComments = iterator.next();
if (!userComments.getMovie().equals(movieController.getMovie()){
iterator.remove();
}
}
userCommntItems = comments;
}
return userCommentItems ;
}