Building select in HQL

-2

I'm starting to use JPA with hibernate and I'm having doubts about the HQL query, I did a little research on the hql Query only that I could not understand much. I want to do this select in hql only I did not understand how to transform it into hql

select idUsuario FROM usuarios where login = 'user'
    
asked by anonymous 24.08.2018 / 18:46

1 answer

3

Suppose a mapped and annotated class with JPA / Hibernate that represents Usuario with these fields, reflecting a table you already have in the database:

@Entity
class Usuario {

  @Id
  private long id;
  private String login;
  (...)

  //getters e setters

}

Now suppose your query method in the database you want to bring a Usuario from a login property:

public Usuario getUsuario(String login) {

  //Pegando a sessao (pressupõe que você já tenha o factory de sessão configurado etc.
  SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
  Session session = sessionFactory.getCurrentSession();

  Query query = session.createQuery("from Usuario user where user.login= :login");
  query.setString("login", login);
  Usuario usuario = (Usuario) query.uniqueResult(); //retorna um Object, por isso o cast obrigatório

}

The important part of your question is here. We define a name for the variable that represents our class (here, user ) and define the property of this class on which we want to base our query ( login , but could be name, age, profession, etc.), accessing the object as we normally do in Java (object.property, that is, user.login ):

Query query = session.createQuery("from Usuario user where user.login= :infoDeLogin");

// Here you link the parameter used in the query with the parameter used in the method.

query.setString("infoDeLogin", login);

See that the query begins with "from Usuario" and not with "select *" , which would normally be expected. This is because, when you want to bring the whole entity, this start is unnecessary, just start with "from" , as done there.

    
24.08.2018 / 19:03