Java programmers from stupid birds to cainiao () detailed discussion on Hibernate (12) Hibernate query sorting component ing

Source: Internet
Author: User

In the actual development process, many users need to sort and display the query results as needed, instead of displaying the results in a disordered order in the database, in this case, we have to sort the data. hibernate provides good support for data sorting. hibernate provides two types of sorting for the queried data results: 1: Database sorting, that is to say, the sorting is completed within the database. 2. Memory sorting, that is, loading data to the memory in the database for sorting. In fact, we generally recommend the second sorting method, because the sorting performance in the database is much higher than the sorting performance in the memory.

 

I. Database sorting

Database sorting mainly uses the order-by attribute in the Set label. The format is order-by = "field name sorting method". For example: order-by = "name ASC" name indicates that the database Field ASC is in ascending order. In hibernate, <set>, <idbag>, <map>, and <list> elements all have the order-by attribute. If this attribute is set, Hibernate uses the order by clause for sorting, using the order-by attribute, we can use the HBM file to execute the generated SQL statement and use the order by query clause to return the sorted result set. Next we will take a specific instance to take a look at the database sorting content

Let's take a look at the relationship between students and teams: first, let's look at the data structure relationship between entities:

Student. Java

Public class student {private string ID; private string name; private string description; private team;. ************ set, get method omitted}

Team. Java

Public class team {private string ID; private string teamname; private set students; ************ set, get method omitted}

From the physical aspect, we can see that students and teams have a many-to-one data relationship. We have read and written this before. I believe everyone is familiar with it. Therefore, we will not write much about the specific configuration file here. Let's take a look at the configuration sorting. Below we will look at the detailed configuration code:

<! -- Returns the student set in descending order of names --> <set name = "Students" table = "studentorder" cascade = "all" Order-by = "name DESC"> <key column = "team_id"> </key> <one-to-learn class = "collection. order. student "/> </set>

It can be seen from the above that, in fact, it is very easy to configure database sorting, Just configure an order-by attribute on the set tag.

The test code is as follows:

Transaction t=session.beginTransaction();               Team team=(Team)session.createQuery("from Team t where t.teamname='team1'").uniqueResult();        Set result=team.getStudents();        for (Iterator iterator = result.iterator(); iterator.hasNext();) {            Student object = (Student) iterator.next();            System.out.println(object.getName());        }               t.commit();

Run this code. Let's take a look at the output of the console:

Test results:

Hibernate: select team0_.id as id1_, team0_.teamname as teamname1_ from teamOrder team0_ where team0_.teamname='team1'Hibernate: select students0_.team_id as team4_1_, students0_.id as id1_, students0_.id as id0_0_, students0_.name as name0_0_, students0_.description as descript3_0_0_, students0_.team_id as team4_0_0_ from studentOrder students0_ where students0_.team_id=? order by students0_.name deschellodefaultbug

From the SQL statement output above, we can see that the data we query is sorted by the name in the student table. So the configuration of database sorting is over.

Ii. Memory sorting

 

Memory sorting, as the name implies, is to sort the results in the memory. After loading the queried results to the memory, the system will wake up sorting. Hibernate also provides memory sorting configuration in the configuration file, that is, the sort attribute. It has two attribute values that can be directly used: unsorted and natural, (ascending). In addition, we can also customize sorting rules by defining a class to implement the comparator interface and the compare method in this interface, you can implement sorting rules in this method. Then, use the Class Name of the custom sorting rule as the property value of sort. Both the <set> and <map> elements have the sort attribute. If this attribute is set, the set objects in the memory are sorted.

The sort attribute of the <set> element is natural, indicating that the strings in the set are naturally sorted. Hibernate uses org. hibernate. persistentsortedset as the set implementation class. The persistentsortedset class implements the java. util. sortedset interface. When the session saves an object, it calls Org. hibernate. type. the wrap () method of the sortedsettype class encapsulates the set attribute of the object as an instance of the sortedset class. The source code of the wrap () method is as follows:

public PersistentCollection wrap(SessionImplementor session, Object collection) {    return new PersistentSortedSet( session, (java.util.SortedSet) collection );  } 

From the source code of the wrap () method, we can see that the set attribute of the object created in the application must be of the Java. util. sortedset type. Otherwise, the above wrap () method will throw classcastexception. In fact, the memory sorting is the same as the database sorting, but the configuration parameters are different. They are all configured in the Set label, so we will not demonstrate it in this example.

3. Component ent ing)

In hibernate, component is the logical component of an object. The fundamental difference between component and object is that component is not identified and is a logical component, this completely belongs to an object. In this way, the fine-grained object division and hierarchical object division are realized in traditional databases, and Object-Oriented Domain Division is achieved.

See:


Take out the common attributes (various contact methods) in user and employee and put them in (abstract to) a separate class. In this way, there are three physical classes, but the entity class only has two tables: user and employee. That is to say, there are only two tables in the database: user and employee.

Next, let's take a look at the Entity and related configuration of user and contact:

User. Java

Public class user {private int ID; private string name; // contact method private contact; * ******************* set, get omitted}

Contact. Java

Public class contact {private string address; private string contacttel; private string email; private string zipcode; * ******************* set, get omitted}

User. HBM. xml

<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

From the configuration point of view, in fact, this place is very easy to understand. The user regards the contact as a part of the composition, but just extracts it from a separate entity class, this also reflects the reusability of the Code. In fact, it is a one-to-one relationship ing.

If you want to generate two tables, Hibernate also provides the relevant configuration mechanism. In fact, you only need to replace the component label with composite-element. That's all, in this way, two tables can be generated.

Related Article

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.