@Override public void saveFriend(ArrayList<AppUser> appUserList) throws InnerException { try { // 循环取appUser for (AppUser appUser : appUserList) { App app = appDao.findById(appUser.getApp().getId()); // 跳过app不存在的appUser if (app == null) continue; Set<AppUser> friends = appUser.getFriends(); Iterator<AppUser> iterator = friends.iterator(); List<AppUser> friendsPersisted = new ArrayList<AppUser>(); // 循环取朋友名 while (iterator.hasNext()) { AppUser friend = iterator.next(); // 查找朋友是否已存在数据库 List<AppUser> list = appUserDao.findByUserIdAndApp(friend.getUserId(), app); // 保存不存在的朋友,若存在,删除列表中的脱管对象,插入持久态对象 if (list.size() == 0) { friend.setCreateTime(System.currentTimeMillis()); appUserDao.save(friend); } else { friendsPersisted.add(list.get(0)); iterator.remove(); } } friends.addAll(friendsPersisted); // 如果appUser不存在,保存;若存在,更新朋友列表 List<AppUser> list = appUserDao.findByUserIdAndApp(appUser.getUserId(), app); if (list.size() == 0) { appUser.setCreateTime(System.currentTimeMillis()); appUserDao.save(appUser); } else { AppUser appUserPersisted = list.get(0); appUserPersisted.setFriends(appUser.getFriends()); appUserDao.update(appUserPersisted); } } } catch (RuntimeException re) { log.error("error saving friend: " + re.toString()); throw new InnerException(); } }