1

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 "";
}
Himanshu
  • 12,071
  • 7
  • 46
  • 61
  • my two cents.. Use a Set to store the names. It will enable you to juse the java Collections class to perform you extraction of subset etc. Please refer following thread on details: https://stackoverflow.com/questions/38768997/java-collection-methods-for-union-intersection-and-set-difference – akshaya pandey Feb 06 '18 at 09:57
  • why do you convert to *arrays*? the `Collection` interface (which is extended by `List`) provides methods for getting differences and duplication: https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html#containsAll-java.util.Collection- / https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html#removeAll-java.util.Collection- / https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html#retainAll-java.util.Collection- – Timothy Truckle Feb 06 '18 at 09:58

0 Answers0