Skip to content

Instantly share code, notes, and snippets.

@bmchild
Last active August 29, 2015 14:14
Show Gist options
  • Save bmchild/0c4862963a97ade70967 to your computer and use it in GitHub Desktop.
Save bmchild/0c4862963a97ade70967 to your computer and use it in GitHub Desktop.
/*
* Class used to filter the User entity
*/
public class UserParameter {
private String userId;
private String lastName;
/* only last 4 digits */
private String ssn;
// getters and setters
}
/*
* Matches either on userId or lastName + last4 digits of SSN
*/
public List<User> findAllByUserIdOrLastNameLastFourSSN( List<UserParameter> parameters ) {
// setup the criteria API to query User
CriteriaBuilder cBuilder = getEntityManager().getCriteriaBuilder();
CriteriaQuery<User> criteriaQuery = cBuilder.createQuery(User.class);
Root<User> root = criteriaQuery.from(User.class);
criteriaQuery.select(root);
// set up lists to store the userId or predicates to match lastName AND last 4 of ssn
List<String> userIds = ArrayList<>();
List<Predicate> nameAndSSNPredicates = new ArrayList<>();
// Loop over parameters, adding predicates and parameters as needed
int i = 0;
for(UserParameter param : parameters) {
if(null == param.getUserId) {
// match lastname + ssn with unique parameters
Predicate predicate = cBuilder.and(
ParameterExpression<String> lastNameParam = cBuilder.parameter(String.class, "lastName" + i);
ParameterExpression<String> ssnParam = cBuilder.parameter(String.class, "ssn" + i);
cBuilder.equal(root.get("lastName"), lastNameParam),
cBuilder.equal( cBuilder.substring(root.get("ssn"), cBuilder.diff( cBuilder.length( root.get("ssn") ), 3), cBuilder.literal(4) ), ssnParam)
);
nameAndSSNPredicates.add(predicate);
} else {
// match to userId
userIds.add(param.getUserId);
}
}
// Add userIds to list of predicates
if(!userIds.isEmpty()) {
nameAndSSNPredicates.add(root.get("userId").in(userIds));
}
// seperate all generated predicates with an OR
Predicate combinedPredicate = cBuilder.or(nameAndSSNPredicates.toArray(new Predicate[nameAndSSNPredicates.size()]));
// Create Query and add parameters
criteriaQuery.where(combinedPredicate);
Query query = getEntityManager().createQuery(criteriaQuery);
int x = 0;
for(UserParameter param : parameters) {
if(null == param.getUserId) {
// only set parameters for lastname and ssn matches
query.setParameter("lastname" + x, param.getLastName());
query.setParameter("ssn" + x, param.getSsn());
}
x++;
}
// run the query
return query.getResultList();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment