How to persist entities inside for loop JPA?

Viewed 5422

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?

2 Answers
Related