Date stateDateBegin,
Date stateDateEnd,
UserHD perfomer) {
CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
CriteriaQuery cq = cb.createQuery();
Root<Request> z = cq.from(Request.class);
Predicate where = cb.conjunction();
Predicate whereCreatedByOrg = null;
if(id != null) {
where = cb.and(where, cb.equal(z.get(Request_.id), id));
}
if(organization != null) {
List<UserHD> listUsers = userHDService.findUsersByOrganization(organization);
for(UserHD us: listUsers) {
if(whereCreatedByOrg == null) {
whereCreatedByOrg = cb.equal(z.get(Request_.createdBy), us);
} else {
whereCreatedByOrg = cb.or(whereCreatedByOrg, cb.equal(z.get(Request_.createdBy), us));
}
}
if(whereCreatedByOrg == null) { // это может быть если в орг-ии нет пользователей - результат поиска пустой
whereCreatedByOrg = cb.isNull(z.get(Request_.createdBy));
}
}
if(createdBy != null) {
where = cb.and(where, cb.equal(z.get(Request_.createdBy), createdBy));
}
if(createdDateBegin != null && createdDateEnd != null) {
where = cb.and(where, cb.between(z.get(Request_.createdDate), createdDateBegin, createdDateEnd));
}
if(description != null) {
where = cb.and(where, cb.like(z.get(Request_.description), "%" + description + "%"));
}
if(text != null) {
where = cb.and(where, cb.like(z.get(Request_.text), "%" + text + "%"));
}
if(serviceObject != null) {
where = cb.and(where, cb.equal(z.get(Request_.serviceObject), serviceObject));
}
if(stateRequest != null) {
where = cb.and(where, cb.equal(z.get(Request_.stateRequest), stateRequest));
}
if(stateDateBegin != null && stateDateEnd != null) {
where = cb.and(where, cb.between(z.get(Request_.stateDate), stateDateBegin, stateDateEnd));
}
if(perfomer != null) {
where = cb.and(where, cb.equal(z.get(Request_.performer), perfomer));
}
// cq.where(cb.and(where, whereCreatedByOrg)); при whereCreatedByOrg == null - NPE
if(whereCreatedByOrg == null) { // whereCreatedByOrg инициализируется только когда задана орг-ия
cq.where(where);
} else {
cq.where(cb.and(where, whereCreatedByOrg));
}
cq.orderBy(cb.desc(z.get(Request_.id)));
cq.select(z);
return getEntityManager().createQuery(cq).getResultList();
}