There are two types of parameters added:
Java code
/**
* Placeholder Parameters
*/
@ SuppressWarnings ("unchecked ")
Public static void test4 (){
Session session = HibernateSessionFactory. currentSession ();
String hql = "from User u where u. id =? ";
Query query = session. createQuery (hql );
Query. setParameter (0, 2 );
List <User> user = query. list ();
System. out. println ("------------ SQL Execution completed ---------------");
For (User us: user ){
System. out. println (us. getName ());
}
}
Note that it starts from 0. If your id is an integer, you must set an integer. If you set the parameter to "2", it will not work!
You can also use the following naming parameters:
Java code
/**
* Named Parameters
*/
@ SuppressWarnings ("unchecked ")
Public static void test5 (){
Session session = HibernateSessionFactory. currentSession ();
String hql = "from User u where u. id =: id ";
Query query = session. createQuery (hql );
Query. setInteger ("id", 2 );
List <User> user = query. list ();
System. out. println ("------------ SQL Execution completed ---------------");
For (User us: user ){
System. out. println (us. getName ());
}
}
It is intuitive to use named parameters.
Paging is relatively simple. set two parameters:
Java code
/**
* Paging
*/
@ SuppressWarnings ("unchecked ")
Public static void test6 (){
Session session = HibernateSessionFactory. currentSession ();
String hql = "from User u ";
Query query = session. createQuery (hql );
Query. setFirstResult (0 );
Query. setMaxResults (5 );
List <User> user = query. list ();
System. out. println ("------------ SQL Execution completed ---------------");
For (User us: user ){
System. out. println (us. getName ());
}
}
As for grouping and sorting, it is the same as writing SQL statements, but the attribute name of the object is written here:
Java code
/**
* Group sorting
*/
@ SuppressWarnings ("unchecked ")
Public static void test7 (){
Session session = HibernateSessionFactory. currentSession ();
String hql = "from User u group by name order by id desc ";
Query query = session. createQuery (hql );
List <User> user = query. list ();
System. out. println ("------------ SQL Execution completed ---------------");
For (User us: user ){
System. out. println (us. getName ());
}
}
Author: dylove98