-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHibernate_HQL.txt
43 lines (29 loc) · 2.2 KB
/
Hibernate_HQL.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
HQL (Hibernate Query Language):
Why ?
- to have more control over the data
- to retrieve data in bulk
- HQL queries allows us to think in terms of objects while generating the queries, unlike SQL where we need to build our quries based on the table and relations in the database.
Query hibernateQuery = session.createQuery("from User"); //select * from User(class name) entity
Query hibernateQuery = session.createQuery("select userName from User"); //select userName(field name) from User(class name) entity
Query hibernateQuery = session.createQuery("select new map(userName, userId) from User"); //return a map for each object conitaining the fields
Query hibernateQueryWithWhere = session.createQuery("from User where userName='New updated user name'"); //select * from User(class name) entity where userName(field name) = ?
pagination in HQL:
hibernateQuery.setMaxResults(2); //set the maximum number of record in one go
hibernateQuery.setFirstResult(3); //set the start position
parameterised queries - to prevent SQL injection attacks:
Query hibernateQueryWithParams = session.createQuery("from User where userId > ?1 and userName = ?2"); //select * from User(class name) entity where userName(field name) = ?
hibernateQueryWithParams.setParameter(1, 0);
hibernateQueryWithParams.setParameter(2, "User With Where");
List usersWithParams = hibernateQueryWithParams.list();
Named Queries:
Named queries allow to write all the common queries at the entity level. And that can be refered anywhere in the application
Named queries provide a way to consolidate all the queries at a perticular place and makes it easy to organize and maintain the queries.
@NamedQuery(name="<nameOfTheQuery>", query="<hqlQuery>") : on top of an entity
with named native query we can also write SQL quries
@NameNativeQuery(name="<nameOfTheQuery>", query="<SQLQuery>", resultClass=<className>) : on top of an entity
e.g.
//named queries
Query namedQuery1 = session.getNamedQuery("user.byId"); //user.byId query is to be defined on an entity with annotation @NamedQuery
namedQuery1.setParameter(1, 5);
List namedQueryUsers = namedQuery1.list();
System.out.println("Named Query User = " + ((User)namedQueryUsers.get(0)).getUserName());