Lore
Lore

Reputation: 1968

Search all not null parameters with Criteria Builder

I have this object

public class ParametriAnagraficaFullMonitorBO implements ParametriFullMonitorBO {
    UserTypeEnum tipoCliente;
    String nome;
    String cognome;
    String denominazione;
    String codiceFiscale;
    String partitaIva;
    String numeroRea;
    String provinciaCciaa;
}

I want to use all members for criteria builder like this:

if (Objects.nonNull(nome)) {
    //queryConditions is a list
    queryConditions.add(criteriaBuilder.equal(root.get("nome"), nome));
}

But it seems strange to me it doesn't exist a mechanism to not use all that identical ifs to check null. I haven't find it yet. Can criteria builder automatically detect null and exclude it?

Upvotes: 0

Views: 68

Answers (1)

Lore
Lore

Reputation: 1968

I have resolved it with reflection (here on a similar method)

for (Method m : searchReportBaseParametersBO.getClass().getMethods()) {
    if (m.getName().startsWith("get") && !m.getName().equals("getClass") && !m.getName().startsWith("getDate")) {
        if (m.invoke(searchReportBaseParametersBO) != null) {
            queryConditions.add(criteriaBuilder.equal(
                    root.get(StringMapper.INSTANCE.firstCharLowercase(
                            m.getName().replaceFirst("^get",""))),
                            m.invoke(searchReportBaseParametersBO)));
        }
    }
}

Upvotes: 1

Related Questions