Search information in the database with validation of Hibernate parameters

Asked

Viewed 115 times

3

Analyze the following situation: will come in request the information of the country that can be {0, 1, 2}. The replacement method will look like this: Nomenclature of the country parameter:

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

    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 will have to do this for about 10 fields. I would have a more viable way to do this validation and avoid so many if? The other fields/parameters just need to perform the exite validation to add more conditions in the AND (String hql += "and ....") . There’s a data field I’ll need to perform BETWEEN.

  • What are these other 10 camps? Would they be from countries as well?

  • @Dherik, no. They would be normal fields, with the exception of between on the registration date. They may come null or with the information on String.

2 answers

3


You can halve the amount of conditionals, using the approach you presented, using a Map and enjoying the same if that concatenates the conditional HQL in the query.

Behold:

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());
}
  • I will implement your idea. I like it +1.

  • 1

    thanks.

0

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

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

The class Usuarios.class contains as attributes the columns returned from the query. 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
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.