When querying using Hibernate, the most used is to query by building HQL. In the process of querying, in addition to using the usual method of querying objects, you also encounter a condition that queries a property, or a set of aggregated results. In this case, we usually need to process the returned structure.
In general, we build hql and customize the type of returned results by setting the Resulttransformer of query, which is generally set to the Map property as follows:
1query = Session.createquery ("hql"); 2 Query.setresulttransformer (CRITERIASPECIFICATION.ALIAS_TO_ENTITY_MAP);
To specify each item of the query result as a map.
However, as hibernate progresses, you can use aggregate query statements, such as list and map, directly in HQL. The following describes the query statements and query results when using list and map respectively. First, the data for the database is as follows:
1Mysql> Select * fromp_dictionary;2 +-----------------+----+---------+------+--------+--------+3 |Dictionary_type|Id|Version|Code|Forbid|Value|4 +-----------------+----+---------+------+--------+--------+5 |County| 1 | 0 | 001 | |Sichuan|6 |County| 2 | 0 | 002 | |Beijing|7 |County| 3 | 0 | 001 | NULL |Sichuan|8 +-----------------+----+---------+------+--------+--------+9 3Rowsinch Set(0.00Sec
The following describes the query statements and query results using list and map, respectively:
Using the list
1 String query = "Select New List (P.code,p.value) from Dictionary P"; 2 List list = session.createquery (query). List (); 3 System.out.println (list); 4 // Results 5 [001, Sichuan], [002, Beijing], [001, Sichuan]]
Using map, first do not specify alias, the result of the key is in the order of query results, using 0, one means key:
1 String query = "Select New Map (p.code,p.value) from Dictionary P"; 2 List list = session.createquery (query). List (); 3 // Results 4 [{1 = Sichuan, 0=001}, {1= Beijing, 0=002}, {1 = Sichuan, 0=001}]
Using map to specify alias, the key in the result is alias:
1 String query = "Select New Map (P.code as code,p.value as value) from Dictionary P"; 2 List list = session.createquery (query). List (); 3 // Results 4 [{value= Sichuan, code=001}, {value= Beijing, code=002}, {value= Sichuan, code=001}]
If you use alias partially, the alias will be used as key, and the ordinal is used instead, and the ordinal is the ordinal of the query result.
1 String query = "Select New Map (P.code as Code,p.value) from Dictionary P"; 2 List list = session.createquery (query). List (); 3 // Results 4 [{1 = Sichuan, code=001}, {1= Beijing, code=002}, {1 = Sichuan, code=001}]
This address: http://www.iflym.com/index.php/code/use-list-set-map-in-hibernate-query.html
Go: Query in hibernate using List,map custom return type