Reputation: 103
I am trying to save entities inside a for loop. But it only save the last entity in the database. my entity looks like following.
@Entity
@Table(name = "users_departments")
public class Users_Departments extends AbstractBaseEntity {
......
}
I have written a common crud method to save the entity in the database as following.
@Override
@Transactional
public T create(T entity) {
entityManager.persist(entity);
entityManager.flush();
entityManager.refresh(entity);
return entity;
}
In the service method, I am saving list of users with department and other details in the database as following.
@Transactional
public List<Users_Departments> addUserstoDepartments(Long deptId,List<Long> useridList){
Users_Departments object = new Users_Departments() ;
List <Users_Departments> userDeptList = new ArrayList<>();
for(int a=0 ; a < useridList.size();a++){
object.setDepartment(departmentDao.find(deptId));
object.setStation(userDao.find(useridList.get(a)));
object.setCreatedDate(new Date());
object.setUpdatedDate(new Date());
Users_Departments newlyCreated = users_departmentsDao.create(object);
userDeptList.add(newlyCreated);
}
return userDeptList;
}
When debugging this method returns the list with updated values, but each and every item has the same value as the "id" . Therefore only the last record is available in the database. I think all other records have been replaced. Is there any reason for that? Can't I create entities inside the for loop? How is it possible?
Upvotes: 3
Views: 6356
Reputation: 4532
You are saving always the same object (hence updating it) move the
Users_Departments object = new Users_Departments() ;
inside the loop to create a new one everytime
Upvotes: 3
Reputation: 7905
You should instantiate the Users_Departments object
each time inside the loop, like this:
List <Users_Departments> userDeptList = new ArrayList<>();
for(int a=0 ; a < useridList.size();a++){
Users_Departments object = new Users_Departments();
object.setDepartment(departmentDao.find(deptId));
object.setStation(userDao.find(useridList.get(a)));
object.setCreatedDate(new Date());
object.setUpdatedDate(new Date());
Users_Departments newlyCreated = users_departmentsDao.create(object);
userDeptList.add(newlyCreated);
}
Upvotes: 4