HQL (Hibernate Query Language)
Object-oriented query language, unlike SQL, the object names in HQL are case-sensitive (except for Java classes and other parts of the property are not case-sensitive); HQL is the object, not the table, and the polymorphism is supported; HQL is mainly operated by query. How query is created:
Queryq = Session.createquery (HQL);
L from person
L from user User Whereuser.name=:name
L from user user where User.name=:nameand User.birthday <: Birthday
Criteria
Criteria is a more object-oriented query method than HQL; How to create criteria:
Criteriacrit = Session.createcriteria (Domainclass.class);
Simple attribute conditions such as: Criteria.add (Restrictions.eq (Propertyname,value)),
Criteria.add (Restrictions.eqproperty (propertyname,otherpropertyname))
Different queries that take advantage of name
1, HQL
Session s=null;
Try {
S=hibernateutil. getsession ();
From Useruser an alias of user to user. Name represents the name of a property in a class
Fromobject is the row of records in all tables, from user to all record rows in the user's corresponding table
String querystring= "from user user where user.name=:n";//query string,hibernate Query Language hql. Class names are case sensitive
Query Query=s.createquery (queryString);//Generate a Query object to query
Query.setstring (0, name);//subscript starting from 0
Query.setstring ("n", name);//with named parameters, you don't need to index the subscript position.
Implementing paged Queries
Query.setfirstresult (0);//starting from line No. 0
Query.setmaxresults (2);//up to 2 records per page
/*query.list ();//List all result sets that meet the criteria
Query.uniqueresult ();//Returns a row of result sets */
If more than one record of the condition is met
List<user> list=query.list ();
for (User u:list) {
System. out. println (U.getid () + ":" +u.getname ());
}
If you know exactly what's on the line
/*useruser= (User) Query.uniqueresult ();
System.out.println (User.getid () + ":" +user.getname ()); */
}finally{
if (s!=null) {
S.close ();
}
}
2. Criteria
Session s=null;
Try {
S=hibernateutil. getsession ();
Criteria C=s.createcriteria (User. Class);//Check the table according to the mapping type
C.add (restrictions. EQ("name", name));//The constraint is added, the name attribute in user is equal to the parameter name
C.add (Restrictions.le ("Birthday", value));//birthday is less than or equal to ...
The above two sentences are equivalent to the criteria C=s.createcriteria (User.class). C.add (Restrictions.eq ("name", name));
List<user> list=c.list ();
for (User user:list) {
System. out. println (User.getid () + ":" +user.getname () + ":" +user.getbirthday ());
}
}finally{
if (s!=null) {
S.close ();
}
}
SQL is a table, HQL is the object, HQL supports polymorphism
HQL and Criteria