我正在使用迭代器遍历对象列表。
List<FormQuestion> questions = regMetadata.getFormQuestions();
Iterator<FormQuestion> iter = questions.iterator();
while (iter.hasNext()){
FormQuestion question = iter.next();
//if invalid question, delete from list
if(question.getModuleType().intValue() == -1) {
iter.remove();
}
}iter.remove()也正在从数据库中删除该对象。有没有办法只从列表(问题)中删除对象,而不从数据库中删除?我使用的是Hibernate和MySQL。
发布于 2017-10-06 21:58:23
我会过滤问题,将它们写入一个新的List
List<FormQuestion> questionsAll = regMetadata.getFormQuestions();
List<FormQuestion> questions = new ArrayList<>();
for (FormQuestion question : questionsAll) {
// add to the list, unless invalid
if (question.getModuleType().intValue() != -1) {
questions.add(question)
}
}另外,我使用for-each循环而不是Iterator。你甚至可以重写它太流了。
发布于 2017-10-06 22:05:22
您的列表由hibernate管理。您应该首先将列表与持久性上下文分离,然后可以从列表中删除,而不是从数据库中删除。我认为这张照片可以帮助你。http://www.objectdb.com/java/jpa/persistence/managed
https://stackoverflow.com/questions/46607324
复制相似问题