Jsf pages don't show newly added values
I'm using Java EE6 and JSF for making a simple CRUD application.
In many of my JSF pages, I have a selectOneMenu for the user to select an existing item. For example, if the user is adding an "Exam", he/she can choose a "Department" from the combo-box, since they have a one-to-many relationship.
The problem is that whenever a new Department is added, the combo-box values are not updated until the session times out. I need to use SessionScoped backing beans, because I need the values to persist across multiple Requests.
Here is a function I'm using to populate the selectOneMenu (not exactly as the example described above, but very similar):
public SelectItem[] getExamsByDepartment(){
if(departmentMaster!=null){
Collection<ExamMaster> examMasterCollection = departmentMaster.getExamMasterCollection();
//Problem: newly added exams aren't shown until session is re-created
if (examMasterCollection != null && examMasterCollection.size() > 0) {
SelectItem[] selectItem = new SelectItem[examMasterCollection.size()];
Iterator<ExamMaster> i = examMasterCollection.iterator();
int count = 0;
while (i.hasNext()) {
ExamMaster tmpExamMaster = i.next();
selectItem[count++] = new SelectItem(tmpExamMaster, tmpExamMaster.getExamName());
}
return selectItem;
}
}
SelectItem[] selectItem = new SelectItem[1];
selectItem[0] = new SelectItem("", "[No exams found]");
return selectItem;
}
I开发者_开发知识库s there any workaround by which I can destroy and re-create the Session? Or any other way by which I can solve this problem?
EDIT: I guess the issue boils down to why the Collection doesn't update after inserting a record, even though the one-to-many relationship is defined in the Persistence class
EDIT 2: Instead of using the collection, I am using a Named Query now, and it fetches the new record as expected. I had assumed that the Collection should be updated automagically. Perhaps that is not true?
Generally it's not a good idea to have session-scoped beans for these cases. Make your bean @ViewScoped
.
Also, whenever you add an item, re-fetch the collection. (this will cover the case when the same user adds and then reads the collection)
EDIT 2: Instead of using the collection, I am using a Named Query now, and it fetches the new record as expected. I had assumed that the Collection should be updated automagically. Perhaps that is not true?
An object's collection is only updated when it's re-sync'd to the database. If you're not explicitly re-syncing to the database, it wouldn't update.
The object in session would have it's copy of the the values and wouldn't need to go back to the database unless something actually told it to.
精彩评论