Hibernate之查询结果排序

一,查询结果排序

HQL和QBC都支持查询结果排序。

HQL采用ORDER BY关键字排序;

QBC采用Order类进行排序。

(1)HQL采用ORDER BY关键字进行排序

在数据库中,默认order by关键字为升序排序,与order by name asc一样,而order by name desc为降序排序。

实例--升序:

package com.lanhuigu.hibernate.test;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import com.lanhuigu.hibernate.entity.Customer;

public class TestHQL {
	public static void main(String[] args) throws Exception{
		Configuration cfg = new Configuration().configure();
		SessionFactory sessionFactory = cfg.buildSessionFactory();
		Session session = sessionFactory.openSession();
		Transaction tr = session.beginTransaction();
		//1.创建Query对象与
		Query query = session.createQuery("from Customer order by name asc");//升序,asc可以去掉
		//2.命名参数动态绑定查询条件
		//query.setString("v_name", "test");
		//2.执行SQL
		List list = query.list();
		//3.输出结果
		for (int i = 0;i<list.size();i++) {
			Customer customer = (Customer) list.get(i);
			System.out.println(customer.getName());
		}
		//4.事务提交
		tr.commit();
		//5.关闭session
		session.close();
	}
}
实例--降序:

将创建的Query对象修改为以下:

Query query = session.createQuery("from Customer order by name desc");//降序,desc不可以去掉,去掉就升序了
(2)QBC采用org.hibernate.criterion.Order进行排序

实例--升序:

package com.lanhuigu.hibernate.test;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.Order;

import com.lanhuigu.hibernate.entity.Customer;

public class TestQBC {
	public static void main(String[] args) throws Exception{
		Configuration cfg = new Configuration().configure();
		SessionFactory sessionFactory = cfg.buildSessionFactory();
		Session session = sessionFactory.openSession();
		Transaction tr = session.beginTransaction();
		//1.创建Criteria对象
		Criteria criteria = session.createCriteria(Customer.class);
		//2.Expression静态方法绑定查询条件,创建的每个Criterion实例就是一个条件
		/*Criterion criterion = Expression.eq("name", "test");
		criteria.add(criterion);*/
		//3.排序
		criteria.addOrder(Order.asc("name"));//升序
		//4.执行SQL
		List list = criteria.list();
		//5.输出结果
		for (int i = 0;i<list.size();i++) {
			Customer customer = (Customer) list.get(i);
			System.out.println(customer.getName());
		}
		//6.事务提交
		tr.commit();
		//7.关闭session
		session.close();
	}
}

实例--降序:

将criteria.addOrder(Order.asc("name"));//升序换为:

criteria.addOrder(Order.desc("name"));//降序

注:可以添加多个排序字段

你可能感兴趣的:(by,order,desc,asc,Hibernate排序)