Для этих случаев удобно использовать JPA Criteria API .
Вот пример для вашего случая:
// get a query builder
CriteriaBuilder builder = em.getCriteriaBuilder();
// build query for entity
CriteriaQuery<Customer> criteriaQuery = builder.createQuery( Customer.class );
// set FROM entity
Root<Customer> tags = criteriaQuery.from( Customer.class );
// get a basic predicate
Predicate p = builder.and();
// add WHERE conditions properly
if (customerNumber != null) {
Predicate conditionPredicate = builder.and(
builder.equal( tags.get("customerNumber"), customerNumber )
);
p = builder.and(p, conditionPredicate);
}
// do the same for customerName and customerFirstName
if (customerName != null) {
Predicate conditionPredicate = builder.and(
builder.equal( tags.get("customerName"), customerName )
);
p = builder.and(p, conditionPredicate);
}
if (customerFirstName != null) {
Predicate conditionPredicate = builder.and(
builder.equal( tags.get("customerFirstName"), customerFirstName )
);
p = builder.and(p, conditionPredicate);
}
// set predicate to query
criteriaQuery.where( p );
// call query and get results
TypedQuery<Customer> q = em.createQuery(criteriaQuery);
List<Customer> o = q.getResultList();
Вот больше примеров если вам нужно