Óscar73
Óscar73

Reputation: 37

Case sensitive query on Hibernate (MySQL)

I want to do some case sensitive queries on my Hibernate project but whenever I use "BINARY" or "COLLATE" on the query to make it case sensitive, I get this error:

org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: BINARY near line 1, column 51 [SELECT u FROM entidades.Usuario u WHERE u.login = BINARY 'XNC' AND u.contrasenya = BINARY 'xnc']

This is the full (and original) code:

Session session = sessionFactory.getCurrentSession();
String select;

try {
        session.beginTransaction();


        select = "SELECT u FROM " + getEntityClass().getName() + " u WHERE u.login ='" + login + "' AND u.contrasenya ='" + contrasenya +"'";
    }

    Query query = session.createQuery(select);
    Usuario usu =  (Usuario) query.uniqueResult();
    session.getTransaction().commit();
    return usu;

    }catch (Exception ex) {
        ex.printStackTrace();
        funciones.mostrarMensajeError(ex.getMessage());
    }

My table is utf8_bin too, so, can somebody help me to do a case sensitive query, please? Thanks. Table on MySQL

Upvotes: 0

Views: 1141

Answers (1)

Andrei Pietrusel
Andrei Pietrusel

Reputation: 556

Just use binary as a function, which is still a valid syntax in SQL, but also accepted by Hibernate:

"... WHERE u.login = binary('" + login + "') AND u.contrasenya = binary('" + contrasenya +"')";

Also, you may want to avoid SQL injection by using query parameters instead of string concatenation.

Upvotes: 1

Related Questions