UserGroupSpecs { public static Specification<UserGroup> isReservedGroup(final boolean isReservedGroup) { return new Specification<UserGroup>() { @Override public Predicate toPredicate(Root<UserGroup> root, CriteriaQuery<?> query, CriteriaBuilder cb) { HashSet<Integer> ids = new HashSet<Integer>(); for (ReservedGroup reservedGroup : ReservedGroup.values()) { ids.add(reservedGroup.getId()); } Predicate inIdsPredicate = root.get(UserGroup_.group).get(Group_.id).in(ids); if (isReservedGroup) { return inIdsPredicate; } else { return inIdsPredicate.not(); } } }; } private  UserGroupSpecs(); static Specification<UserGroup> hasGroupId(final int groupId); static Specification<UserGroup> hasGroupIds(final List<Integer> groupId); static Specification<UserGroup> hasUserId(final int userId); static Specification<UserGroup> hasProfile(final Profile profile); static Specification<UserGroup> isReservedGroup(final boolean isReservedGroup);  }
@Test public void testIsReservedGroup() throws Exception { UserGroup ug1 = _repo.save(newUserGroup()); UserGroup ug2 = _repo.save(newUserGroup()); UserGroup ug3 = _repo.save(newUserGroup()); UserGroup ug4 = _repo.save(newUserGroup()); Map<ReservedGroup, Integer> normalIds = new HashMap<ReservedGroup, Integer>(); for (ReservedGroup reservedGroup : ReservedGroup.values()) { normalIds.put(reservedGroup, reservedGroup.getId()); setReservedGroupId(ug1.getId().getGroupId() - 10 + reservedGroup.getId(), reservedGroup); } try { final int groupId = ug3.getId().getGroupId(); final ReservedGroup group = ReservedGroup.intranet; setReservedGroupId(groupId, group); setReservedGroupId(groupId, group); setReservedGroupId(groupId, group); setReservedGroupId(groupId, group); List<Integer> found = _repo.findGroupIds(isReservedGroup(true)); assertFalse(found.contains(ug1.getId().getGroupId())); assertFalse(found.contains(ug2.getId().getGroupId())); assertTrue(found.contains(groupId)); assertFalse(found.contains(ug4.getId().getGroupId())); found = _repo.findGroupIds(isReservedGroup(false)); assertTrue(found.contains(ug1.getId().getGroupId())); assertTrue(found.contains(ug2.getId().getGroupId())); assertFalse(found.contains(groupId)); assertTrue(found.contains(ug4.getId().getGroupId())); } finally { for (ReservedGroup reservedGroup : ReservedGroup.values()) { setReservedGroupId(normalIds.get(reservedGroup), reservedGroup); } } }