Hibernate query HQL query queries certain Columns

Source: Internet
Author: User

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]);
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.