The user saves a table with a certain list of names of members. My code updates the team for the user without any problem.
My problem now is that what if the user removes a member from the list?
My approach was to:
- Get members that are on this team
List<User> usersOnTeam = User.getUsersWithTeam(teamName);
- Get the names of those users
String[] usersOnTeamArray = new String[usersOnTeam.size()]; for (int i = 0; i < usersOnTeam.size(); i++) { usersOnTeamArray[i] = usersOnTeam.get(i).getUsername(); }
What now? I need some way to compare if the differences between the arrays and update them accordenly.
Also if String[] members
is empty you should remove the team from all members with that team.
public static String saveTeam(String teamName, String[] members) {
//Update team for the user in the database
Team team = getTeam(teamName);
SessionFactory factory = HibernateUtil.GetSessionFactory();
Session session = factory.openSession();
Transaction tx = session.beginTransaction();
//Check if it was removed any user
List<User> usersOnTeam = User.getUsersWithTeam(teamName);
String[] usersOnTeamArray = new String[usersOnTeam.size()];
for (int i = 0; i < usersOnTeam.size(); i++) {
usersOnTeamArray[i] = usersOnTeam.get(i).getUsername();
}
try {
for(String member : members) {
String hql = "FROM User WHERE username= :username";
Query query = session.createQuery(hql);
query.setParameter("username", member);
User user = (User) query.getSingleResult();
if (user != null) {
//Update
user.setTeam(team);
session.merge(user);
}
}
tx.commit();
} catch (HibernateException e) {
if (tx != null) tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
return "";
}