Getting started 06 - Query interface
In addition to using the find () method and cooperate with HQL, we can also query through the instance of the net.sf.hibernate.Query interface, through the Query interface, you can set the query parameter before passing Fill in setxxx () and other methods, fill in the specified parameter value without having to write complete HQL each time, directly look at the example:
Query Query = session.createQuery ("SELECT User.Name from User As User Where User.age =? And user.sex =?");
Query.setInteger (0, 25);
Query.SetCharacter (1, 'm');
List name = query.list ();
For (listiterator itrator = names.listiterator (); item.hasnext ();) {
String name = (string) iterator.next ();
System.out.println ("Name:" Name);
}
When setting the parameter value, must be in accordance with the order set, and use the corresponding type setxxx () method, an example of an execution is as follows:
Log4j: warn no appenders could be bound for logger (net.sf.hibernate.cfg.environment).
Log4J: Warn Please Initialize The log4j system prot in.
Hibernate: SELECT User0_.name AS X0_0_ from user user0_ where (user0_.age =?) And (user0_.sex =?)
Name: Bush
You can replace this method using the named parameter, which can set the parameter value in accordance with a specific order, and have good readability, directly to see an example:
Query Query = session.createQuery ("SELECT User.Name from User As User Where User.age =: Age and User.sex =: SEX");
Query.setInteger ("age", 25);
Query.SetCharacter ("SEX", 'M');
List name = query.list ();
For (listiterator itrator = names.listiterator (); item.hasnext ();) {
String name = (string) iterator.next ();
System.out.println ("Name:" Name);
}
When you set a named parameter, use Query before using: followed by the parameter name, then we can specify the parameter value directly in the setxxx () method, without in accordance with a specific order. We can also write HQL outside the program to avoid hard code in the program, it is very convenient to modify HQL, use the
XML Version = "1.0"?>
Public "- // hibernate / hibernate mapping dtd // en"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
id>
Property>
clas>
SELECT User.name from user as user where user.age =: age and user.sex =: sex
]]]]
query>
hibernate-maping>
Query Query = session.getnamedQuery ("Onlyfun.caterpillar.Queryuser");
Query.setInteger ("age", 25);
Query.SetCharacter ("SEX", 'M');
List name = query.list ();
For (listiterator itrator = names.listiterator (); item.hasnext ();) {string name = (String) item.next ();
System.out.println ("Name:" Name);
}
More about Hibernate queries, you can view the Chapter 9 of the Reference Manual.