D
D
DeNissss44442021-06-07 10:35:22
Hibernate
DeNissss4444, 2021-06-07 10:35:22

Where should HQL queries be implemented?

I started to study HQL under Spring and questions immediately began to appear :) I read various articles about HQL and they give various code options, but for some reason they don’t write where exactly it should be implemented. I understand that a lot of things should be clear if you know the basics of Spring, but I decided to clarify some points here in order to know for sure that I correctly understand how it all works. And so, as I understand it, the most suitable for Spring are named queries, since they can be written once and then simply called?
According to the logic, this part of the code should be written in the model right above the class name?

@NamedQueries({
    @NamedQuery(
        name = "findCompaniesWithWorkerPassport",
        query = "Select c from Company as c, IN(c.workers) as w where w.passport.series = :series")
 
})


Now, when I want to find companies with an employee's passport, logically, I can call this query and I should call it in the Service class, right?
Java
session.getNamedQuery("findCompaniesWithWorkerPassport")
  .setParameter("series", "AS")
  .list()
  .forEach(System.out::println);


The question also arises if we use HQL and we need to write one unpopular query, which, for example, will be used only once in the entire project. Then the named query is clearly not suitable. In this case, do we need to write the name of the request in our repository and implement it already in the Service class? True, or somehow they do it differently here.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Orkhan Hasanli, 2021-06-07
@DeNissss4444

Link to useful source: https://www.baeldung.com/hibernate-named-query

According to the logic, this part of the code should be written in the model right above the class name?

Yes
Now, when I want to find companies with an employee's passport, logically, I can call this query and I should call it in the Service class, right?

As an option, you can in the service. Usually, yes, this is done in the service layer, but no one forbids you from doing this inside the controller or somewhere else.
The question also arises if we use HQL and we need to write one unpopular query, which, for example, will be used only once in the entire project.

In Spring, not only HQL is used, but also Spring Data or Criteria API or JPQL.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question