In hibernate, the object class is queried using hql statements, and the returned result of the list method is a List. The objects encapsulated in the List are divided into the following three situations:
1. When you query all fields, such as "from object class", the objects encapsulated in the list are the object class, And all attributes are filled.
2. query only one field. By default, the Object is encapsulated in the list.
3. query two or more fields. By default, the list encapsulates Object [], and the length is consistent with the number of fields queried.
In the latter two cases, it is not convenient to use the Tag time, because it cannot be directly converted into an object of the object class. The simple solution is:
Usage: In hql, select new package name. Class Name (attribute 1, attribute 2…) is used ......) From Object Class, add the constructor with parameters in the object class, the number and order of parameters and (attribute 1, attribute 2 ......) In this way, the objects of the object class are stored in the list, and the queried attributes are filled, making it easier to use.
Partition: hql queries some fields in multiple tables. select new package name. Table 1 Object Class Name (table 1. Attribute 1, Table 2. Attribute 2 ......) From table 1 entity class, Table 2 entity class where Table 1.ID= table 2.ID( that is, associated fields ), at the same time, in the object class of Table 1 to be returned, add the attributes of table 2 and the Construction Method with parameters, the number and order of parameters and (table 1. attribute 1, table 2. attribute 2 ......) Consistent
For example, to query pid, score, title, totalAccept, totalSubmission, and unSee in Problem
Public class Problem {private int pid; private int score; private int timeLimit; private int memoryLimit; private int totalAccept; private int totalSubmission; private int unSee; private String title; private String description; private String input; private String output; public Problem (int pid, int score, String title, int totalAccept, int totalSubmission, int unSee) {super (); this. pid = pid; this. score = score; this. totalAccept = totalAccept; this. totalSubmission = totalSubmission; this. unSee = unSee; this. title = title;} // omit getter and setter}
The query statement is as follows:
Query query = session. createQuery ("select new Problem (pid, score, title, totalAccept, totalSubmission, unSee) from Problem order by pid"); // query. setFirstResult (firstResult); // paging function // query. setMaxResults (maxResutl); List <Problem> problems = query. list (); // returns the Problem object