Quick Start to Hibernate query

Source: Internet
Author: User

From: http://www.router.net.cn/Article/26665.html

 

If you do not know the persistent identifier of the object to be searched, you need to use hibernate to query. Here, I will share my experience with you and hope it will be useful to you.

Hibernate supports powerful and easy-to-use object-oriented Query Language (hql ). If you want to create a query by programming, Hibernate provides a comprehensive query by criteria (QBC) and Hibernate query by example (QBE) function. You can also use native SQL to describe hibernate queries. hibernate provides additional support for converting result sets into objects.

Execute Query

Hql and native SQL queries are expressed by org. hibernate. query instances. This interface provides methods for parameter binding, result set processing, and running actual queries. You can always obtain a query object through the current session:

  
 
  1. ListCats=Session. Createquery (
  2. "From cat as cat where Cat. Birthdate<? ")
  3. . Setdate (0, date)
  4. . List ();
  5.  
  6. ListMothers=Session. Createquery (
  7. "Select mother from cat as CAT join cat. Mother as mother whereCat. Name=? ")
  8. . Setstring (0, name)
  9. . List ();
  10.  
  11. ListKittens=Session. Createquery (
  12. "From cat as cat whereCat. Mother=? ")
  13. . Setentity (0, PK)
  14. . List ();
  15.  
  16. CatMother= (CAT) Session. createquery (
  17. "Select cat. Mother from cat as cat whereCat=? ")
  18. . Setentity (0, Izi)
  19. . Uniqueresult ();]
  20.  
  21. QueryMotherswithkittens= (CAT) Session. createquery (
  22. "Select mother from cat as mother left join fetch Mother. kittens ");
  23. SetUniquemothers=NewHashset (motherswithkittens. List ());

A query is usually executed when list () is called, and the execution result is fully loaded into a collection in the memory ). The returned object is in the persistent state. If you know that the query returns only one object, you can use the list () shortcut uniqueresult (). Note: The root objects (their collection classes are initialized) are often returned when a set is pre-crawled ). You can use a set to filter repeated objects.

1. iterating results)

In some cases, you can useIterate ()Method To get better performance. This is usually because the expected results already exist in the session or second-level cache. Otherwise,Iterate ()ComparableList ()Slow, and simple queries may also require multiple database accesses:Iterate ()Will first use1Statement to obtain the identifiers of all objects, and then executeNThe attached SELECT statement instantiate the actual object.

  
 
  1. // Fetch IDS
  2. IteratorITER=Sess. Createquery ("from eg. qux Q order by Q. likeliness"). iterate ();
  3. While (ITER. hasnext ()){
  4. QuxQux= (Qux) ITER. Next (); // fetch the object
  5. // Something we couldnt express in the query
  6. If (qux. calculatecomplicatedalgorithm ()){
  7. // Delete the current instance
  8. ITER. Remove ();
  9. // Dont need to process the rest
  10. Break;
  11. }
  12. }

2. Query of tuples

Tuples indicates that a result row contains multiple objects. hibernate queries sometimes return tuples, and each tuples returns an array:

  
 
  1. IteratorKittensandmothers=Sess. Createquery (
  2. "Select kitten, mother from cat kitten join kitten. Mother ")
  3. . List ()
  4. . Iterator ();
  5.  
  6. While (kittensandmothers. hasnext ()){
  7. Object []Tuple= (Object []) kittensandmothers. Next ();
  8. CatKitten=Tuple[0];
  9. CatMother=Tuple[1];
  10. ....
  11. }

3. scalar results

You can specify the attributes of a class in the select clause, or even call the SQL statistics function. Properties or statistical results are identified as "scalar" results (rather than persistence (persistent state) entities ).

 

  
 
  1. IteratorResults=Sess. Createquery (
  2. "Select cat. Color, min (Cat. Birthdate), count (CAT) from Cat" +
  3. "Group by CAT. Color ")
  4. . List ()
  5. . Iterator ();
  6. While (results. hasnext ()){
  7. Object []Row= (Object []) results. Next ();
  8. ColorType= (Color) Row [0];
  9. DateOldest= (Date) Row [1];
  10. IntegerCount= (Integer) Row [2];
  11. .....
  12. }

4. Bind Parameters

The interface query provides question marks (?) for naming parameters and JDBC styles (?) Parameter binding method. Unlike JDBC, Hibernate starts counting parameters from 0. Named parameters indicates the name identifier in the query string. Named parameters has the following advantages:

Named parameters is irrelevant to the order in which the query string appears.

They can appear multiple times in the same query string.

They are self-explanatory.

  
 
  1. // Named parameter (preferred)
  2. QueryQ=Sess. Createquery ("from domesticcat cat whereCat. Name=: Name ");
  3. Q. setstring ("name", "fritz ");
  4. IteratorCats=Q. Iterate ();
  5. // Positional Parameter
  6. QueryQ=Sess. Createquery ("from domesticcat cat whereCat. Name=? ");
  7. Q. setstring (0, "Izi ");
  8. IteratorCats=Q. Iterate ();
  9. // Named parameter list
  10. ListNames=NewArraylist ();
  11. Names. Add ("Izi ");
  12. Names. Add ("fritz ");
  13. QueryQ=Sess. Createquery ("from domesticcat cat where Cat. Name in (: nameslist )");
  14. Q. setparameterlist ("nameslist", names );
  15. ListCats=Q. List ();

5. Paging

If you need to specify the range of result sets (the maximum number of rows to be returned/or the Starting number of rows), you should use the method provided by the query interface:

   
  
  1. QueryQ=Sess. Createquery ("from domesticcat ");
  2. Q. setfirstresult (20 );
  3. Q. setmaxresults (10 );
  4. ListCats=Q. List ();

Hibernate knows how to convert a qualified Query into Native SQL of your database ).

6. scrollable Iteration)

If your JDBC driver supports rolling resuleset, the query interface can use scrollableresults, allowing you to flexibly walk through the query results.

  
 
  1. QueryQ=Sess. Createquery ("select cat. Name, cat from domesticcat cat" +
  2. "Order by CAT. Name ");
  3. ScrollableresultsCats=Q. Scroll ();
  4. If (cats. First ()){
  5.  
  6. // Find the first name on each page of an alphabetical list of cats by name
  7. Firstnamesofpages=NewArraylist ();
  8. Do {
  9. StringName=Cats. Getstring (0 );
  10. Firstnamesofpages. Add (name );
  11. }
  12. While (cats. Scroll (page_size ));
  13.  
  14. // Now get the first page of cats
  15. Pageofcats=NewArraylist ();
  16. Cats. beforefirst ();
  17. IntI=0;
  18. While (page_size>I ++) & cats. Next () pageofcats. Add (cats. Get (1 ));
  19.  
  20. }
  21. Cats. Close ()

Note: To use this function, you must keep the database connection (and cursor) in the open state. If you need to disconnect and use the paging function, use setmaxresult ()/setfirstresult ()

7. External name query (externalizing named queries)

You can define a name query (named queries) in the ing file ). (If your query string contains characters that may be interpreted as XML markup, don't forget to wrap it in CDATA .)

Parameter binding and execution are completed programmatically:

   
  
  1. QueryQ=Sess. Getnamedquery ("bynameandmaximumweight ");
  2. Q. setstring (0, name );
  3. Q. setint (1, minweight );
  4. ListCats=Q. List ();

Pay attention to the actualProgramCodeIt has nothing to do with the query language used. You can also define native SQL queries in the metadata, or store other original query statements in the configuration file, in this way, Hibernate can be centrally managed for migration purposes.

Note that The query declared in the element must have a globally unique name. The query declared in the element automatically has a global name, which is limited by the full name of the class. For example, eg. Cat. bynameandmaximumweight.

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.