HQL is short for Hibernate Query Language, that is, hibernate Query Language: HQL adopts the Object-Oriented Query Method. HQL queries provide more abundant and flexible query features. Therefore, Hibernate sets the HQL query method as the standard query method officially recommended. HQL queries cover all functions of Criteria queries, provides query methods similar to standard SQL statements, and more object-oriented encapsulation.
In HQL, you can directly query From your object:
Java code
/**
* Easy to use
*/
@ SuppressWarnings ("unchecked ")
Public static void test1 (){
Session session = HibernateSessionFactory. currentSession ();
String hql = "from User u ";
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 ());
}
}
Class can be followed by an alias
To query a column separately, you can use the following method:
Java code
/**
* Query a column
*/
@ SuppressWarnings ("unchecked ")
Public static void test2 (){
Session session = HibernateSessionFactory. currentSession ();
String hql = "select name from User u ";
Query query = session. createQuery (hql );
List <String> user = query. list ();
System. out. println ("------------ SQL Execution completed ---------------");
For (String us: user ){
System. out. println (us );
}
}
To query several columns, the returned content is different:
Java code
/**
* Query certain Columns
*/
@ SuppressWarnings ("unchecked ")
Public static void test3 (){
Session session = HibernateSessionFactory. currentSession ();
String hql = "select id, name from User u ";
Query query = session. createQuery (hql );
List user = query. list ();
System. out. println ("------------ SQL Execution completed ---------------");
For (Object obj: user ){
Object [] arrObj = (Object []) obj;
System. out. println (arrObj [0] + "/t -->/t" + arrObj [1]);
}
}