用户保存一个包含特定成员名称列表的表。 我的代码为用户更新团队没有任何问题。
我现在的问题是,如果用户从列表中删除了某个成员,该怎么办?
我的方法是:
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(); }
现在怎么办?我需要一些方法来比较数组之间的差异并更新它们。
如果String[] members
为空,则应从该团队的所有成员中删除该团队。
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 "";
}