Hibernate HQL syntax and related foreign key associations

Source: Internet
Author: User

For example, for the Tuser class

1. Entity Query

String hql = " from TUser";

Executing this statement returns the records of the Tuser and the Tuser subclass.

Note: If the TUser class has a foreign key, the query will complain!

Workaround: Select Alias. property from class as Alias. No aliases. Property still complains!

hql = "from java.lang.Object"

Returns a record of all the library tables in the database.

WHERE statement

hql = "from TUser as user where user.name='yyy'";

Where as can be omitted also the same

hql = "from TUser user where user.name='yyy'";

In the WHERE clause, we can set conditions by comparing operators, such as: =, <>,,, >=, <=, between, not between, in, don't in, be, like, and so on.

2. Property Query

List list = session.createQuery("select user.name, user.age from TUser as user").list();

You can also dynamically construct methods of object instances in HQL to encapsulate data.

List list = session.createQuery("select new TUser(user.name, user.age) from TUser as user").list();
Iterator it = list.iterator();
while(it.hasNext() ) {
TUser user = (TUser)it.next();
System.out.println(user.getName());
}

Note, however, that the Tuser object here is only encapsulated for the name and age attributes, and that no other state is assigned, so it cannot be used for update operations.

You can also use statistical functions in the HQL SELECT clause

"select count(*) ,min(user.age) from TUser as user"

You can also use the DISTINCT keyword to delete duplicate records.

select distinct user.name from TUser as user;

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.