list and iterate methods for the 1.Query interface:
Iterate () Method:
Return the query results as an Iterator. Ifthe query contains multiple results pre row, the results is returned in Aninstance ofobject[].
Entities returned as results is initialized OnDemand. The first SQL query returns identifiers only.
(The returned entity is initialized only when it is used, and only the identifier (that is, id) of the entity is returned when the method query is executed)
list () method:
Return the query results as a List. If Thequery contains multiple results pre row, the results is returned in Aninstance ofobject[].
2. The difference between the two:
For the list () method of the query interface, the object that gets the query can be implemented with the iterate () method, but each object returned by the list () method is complete (each property in the object is populated with the fields in the table), and iterator () The object returned by the method contains only the primary key value (identifier), and Hibernate sends the SQL statement to the database again to get the property values of the object only if you are manipulating the object in iterator.
3. Example:
Session session =sessionfactory.opensession ();
Transaction tx =null;
list<people> list = null;
iterator<people> iter = null;
Try
{
tx= session.begintransaction ();
Query query = Session.createquery ("from people");
/* Using the Iterate method Iterator<people> iter = (iterator<people>) query.iterate (); while (Iter.hasnext ()) { Session.delete (Iter.next ()); } */ |
Comparison of the efficiency of the two ways to delete records in a database (if 5 records are found):
Iterate () Method: Executes 6 SELECT statements and 5 DELETE statements
List () method: Executes 1 SELECT statements and 5 DELETE statements
The list is more efficient at this point
Using the list method List = (list<people>) query.list (); for (iterator<people> iter = List.iterator (); Iter.hasnext ();) // { Session.delete (Iter.next ()); // } |
Call the Iterate method before the session closes and then use ITER to access the people object to prove that the iterate method did not return the complete object iter = (iterator<people>) query.iterate (); |
Tx.commit ();
}catch(Exception ex)
{
if (null ! = TX)
{Tx.rollback ();}
}finally
{Session.close ();}
When the session is closed, it is impossible to send SQL statements to the database to get the properties of the object (that is, to populate the complete object), then throws the sessionexception exception hint "Session is closed!" while (Iter.hasnext ()) { System.out.println (Iter.next (). GetId ()); } |
For other methods of the query interface, see the API Help documentation
Reprint Please specify source: http://blog.csdn.net/jialinqiang/article/details/8718437