Building select in HQL

Asked

Viewed 862 times

-1

I’m starting to use JPA with Hibernate and I’m having doubts about the HQL query, I did some research on the Query hql but I couldn’t understand much. I want to do this select in hql only I did not understand how to turn it into hql

select idUsuario FROM usuarios where login = 'user'

1 answer

4


Suppose a class mapped and annotated 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 bank you want to bring one Usuario from a property login:

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 about your question is here. We have defined any name for the variable that represents our class (here, user) and define the ownership of that 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, ie, user.login):

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

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

query.setString("infoDeLogin", login);

See that the query starts with "from Usuario" and not with a "select *", that would normally be expected. That’s because, when you want to bring the whole entity, that start is unnecessary, just start with the "from", as done there.

  • Thank you very much, I had researched how to do this, only I had not managed to understand that after the FROM would come the entity created, by the examples I had read I thought it was something related to the table FROM nome_tabela now you’re pretty good with that explanation of yours. Super thank you.

  • In fact, your thinking is correct. "Behind the scenes", the framework, when creating the SQL query converts the entity into the table for which the object Usuario is mapped. The difference is that in HQL, you use Java objects and properties instead of tables and database fields.

Browser other questions tagged

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