6.1 Named Queries
Hibernate allows you not to store queries directly in the code. Instead, he suggests giving queries names and storing them separately as annotations. Well, then take the desired request directly by its name. Example:
@org.hibernate.annotations.NamedQueries({
@org.hibernate.annotations.NamedQuery(name = "Employee_FindById",
query = "from Employee where id = :id"),
@org.hibernate.annotations.NamedQuery(name = "Employee_FindAllEmployes",
query = "from Employee"),
@org.hibernate.annotations.NamedQuery(name = "Employee_UpdateEmployeeName",
query = "Update Employee set name = :newName where id = :id"),
...
})
Annotations can be added before any Entity class: query names are not tied to any Entity.
You can also add various parameters to the query (query):
@org.hibernate.annotations.NamedQuery(
name = "Employee_ FindAllEmployes",
query = "from Employee",
timeout = 1,
fetchSize = 10,
cacheable = true,
cacheMode = "GET"
)
Using such requests is very simple - for this you need to use a method createNamedQuery
instead of a method createQuery
:
Query<Employee> query = session.createNamedQuery("Employee_FindAllEmployes", Employee.class);
List<Employee> resultLIst = query.list();
6.2 NativeQuery
And another simple but very useful thing is NativeQuery .
If you don't want to use HQL, but want to use Hibernate for entity mapping, then you can write queries in good old SQL. Nobody limits you.
To do this, you just need to call the method createNativeQuery()
, instead of createQuery()
.
NativeQuery<Employee> query = session.createNativeQuery("select * from employee", Employee.class);
List<Employee> resultLIst = query.list();
You just write createNativeQuery
and everything will work as before. This method returns an object of type NativeQuery , which supports all the methods that the Query class supports . Nothing will change for you.
Additionally, Native SQL Query can also be stored as Named Queries .
@org.hibernate.annotations.NamedNativeQueries(
@org.hibernate.annotations.NamedNativeQuery(name = "Employee_GetAll",
query = "select * from employee",
resultClass = Employee.class)
)
And of course, here is the code for working with them:
NativeQuery<Employee> query = session.createNamedQuery("Employee_GetAll", Employee.class);
List<Employee> resultLIst = query.list();