學習Hibernate時我們會學習到hql語句,他與sql語句最重要的區別是:hql針對的是實體類的相關屬性,sql針對的數據庫表的相關列。接下來我們來認識和彙總hql與sql語句的幾個區別:
五)hibernate專用查詢
(0)hibernate中的查詢方式
>>session.get(字節碼,1)
>>session.load(字節碼,1)
>>query.list()
>>query.uniqueResult()
>>HQL查詢【複雜,靈活,用途最廣】
>>對象導航查詢
(1)SQL和HQL的區別
HQL:
>>HQL是hibernate專用查詢方式
>>hibernate用專用的技術將HQL轉成SQL,此時會時時間的開銷
>>HQL是完全面向對象的語法形式,即在HQL中只能出現類,屬性,和一些操作符和關健字,例如:sum(),order by
SQL:
>>SQL是任何關係型數據庫通用的查詢方式
>>SQL是直接面向數據庫的,無需轉換
>>SQL是完全面向關係的語法形式,即在SQL中只能出現表,字段,和一些操作符和關健字,例如:sum(),order by
下面是熟悉和練習hql語句的題目:
(2)需求
(A)查詢ID為1的客户訂單信息
from Customer where id = 1
(B)查詢姓名為“XX”的客户訂單信息
from Customer where name = '牛人'
(C)使用別名,查詢姓名為“XX”的客户訂單信息
(D)共有幾個對象,共有幾個客户,共有幾個訂單,多態查詢(是指查詢出當前類或所有子類的實例)
from java.lang.Object
(E)查詢所有訂單,按價格降序排列
from Order o order by o.price DESC
(F)分頁查詢所有訂單,每頁顯示3條記錄
//從第幾條記錄-1開始顯示
query.setFirstResult(6);
//最多顯示幾條記錄
query.setMaxResults(3);
(G)查詢價格最貴的一個訂單
from Order o order by o.price desc
query.setFirstResult(0);
query.setMaxResults(1);
(H)查詢姓名為“XX”的客户訂單信息,動態綁定參數,方式一:通過名字綁定,名字以:開頭
(I)查詢姓名為“XX”的客户訂單信息,動態綁定參數,方式二:通過佔位符?綁定,下標多0開始(個人提倡)
(J)查詢姓名為“XX”的客户訂單信息,動態綁定參數,方式三:在映射文件中定義命名HQL查詢語句
<query name="findCustomerByAge">
<![CDATA[
from Customer c where c.age < ?
]]>
</query>
(K)查詢姓"X"的,且年齡不介於10-20歲之間的客户
from Customer c where c.name like ? and c.age not between ? and ?
(L)使用投影查詢,查詢“XX”客户姓名,年齡,描述
select c.name,c.age from Customer c where c.name = '牛人'
注意:返回值,是一個數組的數組
(M)查詢訂單總數,訂單總價格,最便宜訂單,最昂貴訂單,訂單平均價格
select count(o),sum(o.price),min(o.price),max(o.price),avg(o.price) from Order o
(N)按客户分組,查詢訂單總價
SQL:
select customers_id,sum(price)
from orders
group by customers_id;
HQL:
select o.customer.id,sum(o.price) from Order o group by o.customer.id;
(3)HQL常用API
>>Query query = session.createQuery();
>>Query query = session.getNamedQuery();
>>query.setString("","");
>>query.setInt("","");
>>Object obj = query.uniqueResult();
>>List list = query.list();
以下代碼是對A-N題目的實現:
package example.hql;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;
import example.utils.HibernateUtils;
public class CustomerOrderDao {
/**
* 查詢ID為1的客户訂單信息
*/
@Test
public void test01(){
Session session=HibernateUtils.getSession();
Transaction t=session.getTransaction();
try{
t.begin();
String hql="from Customer where id=1";
Query query=session.createQuery(hql);
Customer c= (Customer) query.uniqueResult();
System.out.println("顧客的姓名:"+c.getName()+"顧客的年齡是:"+c.getAge());
//對象導航查詢
for(Order o:c.getOrderSet()){
System.out.println("訂單號:"+o.getOrderNo());
}
t.commit();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
t.rollback();
}finally{
HibernateUtils.closeSession();
}
}
/**
* 查詢姓名為“XX”的客户訂單信息(如:牛人2號)和使用別名,查詢姓名為“XX”的客户訂單信息
*/
@Test
public void test02(){
Session session=HibernateUtils.getSession();
Transaction t=session.getTransaction();
try{
t.begin();
String hql="from Customer where name='牛人2號'";
Query query1=session.createQuery(hql);
Customer c1= (Customer) query1.uniqueResult();
for(Order o:c1.getOrderSet()){
System.out.println("牛人2號顧客的訂單編號:"+o.getOrderNo()+",價格:"+o.getPrice());
}
hql="from Customer c where c.name='牛人'";
Query query2=session.createQuery(hql);
Customer c2= (Customer) query2.uniqueResult();
for(Order o:c2.getOrderSet()){
System.out.println("牛人顧客的訂單編號:"+o.getOrderNo()+",價格:"+o.getPrice());
}
t.commit();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
t.rollback();
}finally{
HibernateUtils.closeSession();
}
}
/**
* 共有幾個對象,共有幾個客户,共有幾個訂單,多態查詢(是指查詢出當前類或所有子類的實例)
*/
@Test
public void test03(){
Session session=HibernateUtils.getSession();
Transaction t=session.getTransaction();
try{
t.begin();
String hql="from java.lang.Object";
Query query=session.createQuery(hql);
List list = query.list();
System.out.println(list.size());
t.commit();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
t.rollback();
}finally{
HibernateUtils.closeSession();
}
}
/**
* 查詢所有訂單,按價格降序排列
*/
@Test
public void test04(){
Session session=HibernateUtils.getSession();
Transaction t=session.getTransaction();
try{
t.begin();
String hql="from Order order by price ";
Query query=session.createQuery(hql);
List<Order> list = query.list();
for(Order o:list){
System.out.println("訂單編號是:"+o.getOrderNo());
}
t.commit();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
t.rollback();
}finally{
HibernateUtils.closeSession();
}
}
/**
* 分頁查詢所有訂單,每頁顯示3條記錄
*/
@Test
public void test05(){
Session session=HibernateUtils.getSession();
Transaction t=session.getTransaction();
try{
t.begin();
String hql="from Order";
Query query=session.createQuery(hql);
query.setFirstResult(0);
query.setMaxResults(3);
List<Order> list = query.list();
System.out.println("每一頁的訂單數目是:"+list.size());
for(Order o:list){
System.out.println("訂單編號是:"+o.getOrderNo());
}
t.commit();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
t.rollback();
}finally{
HibernateUtils.closeSession();
}
}
/**
* 查詢價格最貴的一個訂單
*/
@Test
public void test06(){
Session session=HibernateUtils.getSession();
Transaction t=session.getTransaction();
try{
t.begin();
String hql="from Order order by price desc";
Query query=session.createQuery(hql);
query.setFirstResult(0);
query.setMaxResults(1);
Order o= (Order) query.uniqueResult();
System.out.println("訂單編號是::"+o.getOrderNo());
t.commit();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
t.rollback();
}finally{
HibernateUtils.closeSession();
}
}
/**
* 查詢姓名為“XX”的客户訂單信息,動態綁定參數,方式一:通過名字綁定,名字以:開頭
*/
@Test
public void test07(){
Session session=HibernateUtils.getSession();
Transaction t=session.getTransaction();
try{
t.begin();
String hql="from Customer c where c.name=:cname";
Query query=session.createQuery(hql);
query.setString("cname", "牛人");
Customer c= (Customer) query.uniqueResult();
System.out.println(c.getOrderSet().size());
t.commit();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
t.rollback();
}finally{
HibernateUtils.closeSession();
}
}
/**
* 查詢姓名為“XX”的客户訂單信息,動態綁定參數,方式二:通過佔位符?綁定,下標多0開始(個人提倡)
*/
@Test
public void test08(){
Session session=HibernateUtils.getSession();
Transaction t=session.getTransaction();
try{
t.begin();
String hql="from Customer c where c.name=?";
Query query=session.createQuery(hql);
query.setString(0, "牛人");
Customer c= (Customer) query.uniqueResult();
System.out.println(c.getOrderSet().size());
t.commit();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
t.rollback();
}finally{
HibernateUtils.closeSession();
}
}
/**
* 查詢姓名為“XX”的客户訂單信息,動態綁定參數,方式三:在映射文件中定義命名HQL查詢語句
* <![CDATA[裏面轉移為字符串]]>
*/
@Test
public void test09(){
Session session=HibernateUtils.getSession();
Transaction t=session.getTransaction();
try{
t.begin();
Query query=session.getNamedQuery("findCustomerByAge");
query.setInteger(0, 12);
List list=query.list();
System.out.println("人數是:"+list.size());
t.commit();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
t.rollback();
}finally{
HibernateUtils.closeSession();
}
}
/**
* 查詢姓"X"的,且年齡不介於10-20歲之間的客户
*/
@Test
public void test10(){
Session session=HibernateUtils.getSession();
Transaction t=session.getTransaction();
try{
t.begin();
String hql="from Customer c where c.name like ? and c.age not between ? and ?";
Query query=session.createQuery(hql);
query.setString(0, "%牛%");
query.setInteger(1, 10);
query.setInteger(2, 20);
List<Customer> list = query.list();
for(Customer c : list){
System.out.println(c.getName()+":"+c.getAge());
}
t.commit();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
t.rollback();
}finally{
HibernateUtils.closeSession();
}
}
/**
*使用投影查詢,查詢“XX”客户姓名,年齡
**/
@Test
public void test11(){
Session session=HibernateUtils.getSession();
Transaction t=session.getTransaction();
try{
t.begin();
String hql="select c.name,c.age from Customer c where c.name like ?";
Query query=session.createQuery(hql);
query.setString(0, "%牛%");
List<Object[]> list = query.list();
for(Object[] o : list){
System.out.println(o[0]+":"+o[1]);
}
t.commit();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
t.rollback();
}finally{
HibernateUtils.closeSession();
}
}
/**
*查詢訂單總數,訂單總價格,最便宜訂單,最昂貴訂單,訂單平均價格
*/
@Test
public void test12(){
Session session=HibernateUtils.getSession();
Transaction t=session.getTransaction();
try{
t.begin();
String hql="select count(o),sum(o.price),min(o.price),max(o.price),avg(o.price) from Order o";
Query query=session.createQuery(hql);
List<Object[]> list = query.list();
for(Object[] obj : list){
System.out.println("訂單總數:"+obj[0]);
System.out.println("訂單總價格:"+obj[1]);
System.out.println("最便宜訂單:"+obj[2]);
System.out.println("最昂貴的訂單:"+obj[3]);
System.out.println("訂單平均價格:"+obj[4]);
}
t.commit();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
t.rollback();
}finally{
HibernateUtils.closeSession();
}
}
/**
*按客户分組,查詢訂單總價
**/
@Test
public void test13(){
Session session=HibernateUtils.getSession();
Transaction t=session.getTransaction();
try{
t.begin();
String hql="select o.customers.id,sum(o.price) from Order o group by o.customers.id";
Query query=session.createQuery(hql);
List<Object[]> list = query.list();
for(Object[] o : list){
System.out.println(o[0]+":"+o[1]);
}
t.commit();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
t.rollback();
}finally{
HibernateUtils.closeSession();
}
}
}