Search for information in the database with Hibernate parameter validation

3

Analyze the following situation: request will provide country information that can be {0, 1, 2} . The repository method will look like this: Country Parameter Naming:

  • 0: Bring all countries;
  • 1: National only (Brazil)
  • 2: International only

    public List<View> getDto(Request request) {
        Session session = getSession();
        session.beginTransaction();
    
        String hql = "select v from view v where 1=1 ";
    
        if(0 != request.getCountry()) {
            String hql += "and country = :country";
        }
    
        List<View> view = session.createQuery(hql, View.class).getResultList();
    
        if(0 != request.getCountry()) {
            session.setParameter(":country", request.getCountry());
        }
        return view;
    
    }
    

I'll have to do this for about 10 camps. Would you have a more feasible way to do this validation and avoid so many if ? The other fields / parameters just need to perform exite validation to add more conditions in AND (String hql += "and ....") . There is also a date field that I need to perform a BETWEEN .

    
asked by anonymous 15.08.2018 / 16:30

2 answers

3

You can halve the amount of conditionals by using the approach you've presented, using Map and taking advantage of the same if that concatenates the HQL conditional in the query.

See:

String hql = "select v from view v where 1 = 1 ";

Map<String, Object> map = new HashMap<>();

if(0 != request.getCountry()) {
    map.put("country", request.getCountry());
    String hql += "and country = :country ";
}

// itera por todos os campos salvos no map e coloca na session como parâmetro
for (Map.Entry<String, Object> entry: map.entrySet()) {
    session.setParameter(entry.getKey(), entry.getValue());
}
    
15.08.2018 / 17:43
0

To show how I used the example above. If someone needs to:

session.beginTransaction();
Query query = session.createSQLQuery(sql);
map.forEach(query::setParameter);
List result = query.setResultTransformer(Transformers.aliasToBean(Usuarios.class)).list();
session.close();

The Usuarios.class class contains the columns returned from the query as attributes. For example:

SELECT nome, email FROM usuários where ativo = 1

public class Usuarios {
    private String nome;
    private String email;

    // Não precisa dos getters e setters neste caso
}
    
20.08.2018 / 15:27