Remove method of the List is not working

118 views Asked by At

I am creating a session variable in one controller-:

List<Employee> emp = new ArrayList<Employee>()
emp = Employee.findAllByLevel(proj_lev.level_no)
session.employee_list = emp

render(view: "add_members", model: [proj_lev:proj_lev , proj_lev_right:proj_lev_right , employee:session.employee_list])

In another controller I am accessing the session variable and using the remove method of the List but the list is not changing-:

render "${session.employee_list}"
def emp_added = Employee.get(params.int('employee_id'))
session.employee_list.remove(emp_added)
render "${session.employee_list}"

The view in the GSP is-:

 [tearp.Employee : 2, tearp.Employee : 5, tearp.Employee : 8, tearp.Employee : 9, tearp.Employee : 10][tearp.Employee : 2, tearp.Employee : 5, tearp.Employee : 8, tearp.Employee : 9, tearp.Employee : 10]
2

There are 2 answers

0
akhil verma On BEST ANSWER

make a list of employee to be removed , and then remove this list from "added employees" and add this list to "all employees"

0
dsharew On

Have you override equals method on Employee domain object? I think that is the problem.

When you say this ( with out overriding the equals method):

session.employee_list.remove(emp_added)

It will first search the object in the list by its hashcode and every time you fetch an object from db using Employee.get(..) hibernate creates new object even for the same record, so every new object has new hashcode and list.remove() method wont work as far as the object is not found on the list.

Possible Solution:

add this method on your Employee domain class:

@Overrid
boolean equals(Employee employee){

return this.id == employee?.id

}