hibernate之HQL语句

1. 什么是hql

HQL是Hibernate Query Language的缩写

2. hql和sql区别/异同

HQL                                                   SQL

类名/属性                                             表名/列名

区分大小写,关键字不区分大小写                      不区分大小

别名                                                         别名

?,从下标0开始计算位置(hibernate5之后不支持)  ?,从顺序1开始计算位

命名参数                                            不支持:命名参数

面向对象的查询语言                                 面向结构查询语言

3. 处理返回的结果集

单个对象

select 没有逗号

Object[]

b.bookId, b.bookName

Map

new Map(b.bookId as bid, b.bookName as bname)

new 构造方法(attr1,attr2)

new Book(b.bookId, b.price)    单个列段

代码演示如下:

工具类:

PageBean

package com.hxc.five.util;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

/**
 * 分页工具类
 *
 */
public class PageBean {

    private int page = 1;// 页码

    private int rows = 3;// 页大小

    private int total = 0;// 总记录数

    private boolean pagination = true;// 是否分页
    // 获取前台向后台提交的所有参数
    private Map<String, String[]> parameterMap;
    // 获取上一次访问后台的url
    private String url;

    /**
     * 初始化pagebean
     *
     * @param req
     */
    public void setRequest(HttpServletRequest req) {
        this.setPage(req.getParameter("page"));
        this.setRows(req.getParameter("rows"));
        // 只有jsp页面上填写pagination=false才是不分页
        this.setPagination(!"fasle".equals(req.getParameter("pagination")));
        this.setParameterMap(req.getParameterMap());
        this.setUrl(req.getRequestURL().toString());
    }

    public int getMaxPage() {
        return this.total % this.rows == 0 ? this.total / this.rows : this.total / this.rows + 1;
    }

    public int nextPage() {
        return this.page < this.getMaxPage() ? this.page + 1 : this.getMaxPage();
    }

    public int previousPage() {
        return this.page > 1 ? this.page - 1 : 1;
    }

    public PageBean() {
        super();
    }

    public int getPage() {
        return page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public void setPage(String page) {
        this.page = StringUtils.isBlank(page) ? this.page : Integer.valueOf(page);
    }

    public int getRows() {
        return rows;
    }

    public void setRows(int rows) {
        this.rows = rows;
    }

    public void setRows(String rows) {
        this.rows = StringUtils.isBlank(rows) ? this.rows : Integer.valueOf(rows);
    }

    public int getTotal() {
        return total;
    }

    public void setTotal(int total) {
        this.total = total;
    }

    public void setTotal(String total) {
        this.total = Integer.parseInt(total);
    }

    public boolean isPagination() {
        return pagination;
    }

    public void setPagination(boolean pagination) {
        this.pagination = pagination;
    }

    public Map<String, String[]> getParameterMap() {
        return parameterMap;
    }

    public void setParameterMap(Map<String, String[]> parameterMap) {
        this.parameterMap = parameterMap;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    /**
     * 获得起始记录的下标
     *
     * @return
     */
    public int getStartIndex() {
        return (this.page - 1) * this.rows;
    }

    @Override
    public String toString() {
        return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination
                + ", parameterMap=" + parameterMap + ", url=" + url + "]";
    }

}

StringUtils

package com.hxc.five.util;

public class StringUtils {
    // 私有的构造方法,保护此类不能在外部实例化
    private StringUtils() {
    }

    /**
     * 如果字符串等于null或去空格后等于"",则返回true,否则返回false
     *
     * @param s
     * @return
     */
    public static boolean isBlank(String s) {
        boolean b = false;
        if (null == s || s.trim().equals("")) {
            b = true;
        }
        return b;
    }

    /**
     * 如果字符串不等于null或去空格后不等于"",则返回true,否则返回false
     *
     * @param s
     * @return
     */
    public static boolean isNotBlank(String s) {
        return !isBlank(s);
    }

}
hql语句的测试类 HqlTest 
package com.hxc.five.test;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.hxc.four.entity.Book;
import com.hxc.three.id.SessionFactoryUtils;

public class HqlTest {
    private Session session;
    private Transaction transaction;

    @Before
    public void before() {
        session = SessionFactoryUtils.openSession();
        transaction = session.beginTransaction();
    }

    @After
    public void after() {
        transaction.commit();
        session.close();
    }

    /**
     * 返回对象(多个)
     */
    @Test
    public void testList1() {
        Query query = session.createQuery("from Book");
        List<Book> list = query.list();
        for (Book b : list) {
            System.out.println(b);
        }
    }

    /**
     * 返回单个列段,用字符串就可以接受
     */
    @Test
    public void testList2() {
        Query query = session.createQuery("select b.bookName as ss from Book b");
        List<String> list = query.list();
        for (String b : list) {
            System.out.println(b);
        }
    }

    /**
     * 查两个列段及以上,默认返回的是Object【】
     */
    @Test
    public void testList3() {
        Query query = session.createQuery("select b.bookId,b.bookName as ss from Book b");
        List<Object[]> list = query.list();
        for (Object[] b : list) {
            System.out.println(Arrays.toString(b));
        }
    }

    /**
     * 注意map是函数,所以不区分大小写,返回的是map集合
     */
    @Test
    public void testList4() {
        Query query = session.createQuery("select new mAp(b.bookId,b.bookName) from Book b");
        List<Map> list = query.list();
        for (Map b : list) {
            System.out.println(b);
        }
    }

    /**
     * 查两个列段及以上,也可返回对象,前提是有对应的构造函数
     */
    @Test
    public void testList5() {
        Query query = session.createQuery("select new Book(b.bookId,b.bookName) from Book b");
        List<Book> list = query.list();
        for (Book b : list) {
            System.out.println(b);
        }
    }

    /**
     * HQL语句支持占位符
     */
    @Test
    public void testList6() {
//        Query query = session.createQuery("from Book where bookId = :bookId");
//        query.setParameter("bookId", 1);
//        Book b = (Book) query.getSingleResult();
//        System.out.println(b);

        Query query = session.createQuery("from Book where bookId in (:bookIds)");
        query.setParameterList("bookIds", new Integer[] {1,2,4});
//        List<Integer> params = new ArrayList<Integer>();
//        params.add(1);
//        params.add(2);
//        params.add(4);
//        query.setParameterList("bookIds", params);
        List<Book> list = query.list();
        for (Book b : list) {
            System.out.println(b);
        }
    }

    /**
     * HQL支持连接查询
     */
    @Test
    public void testList7() {
        Query query = session.createQuery("select o.orderNo,oi.quantity from Order o,OrderItem oi where o = oi.order");
        List<Object[]> list = query.list();
        for (Object[] b : list) {
            System.out.println(Arrays.toString(b));
        }
    }

    /**
     * HQL支持聚合函数
     */
    @Test
    public void testList8() {
        Query query = session.createQuery("select count(*) from Book");
        Long singleResult = (Long) query.getSingleResult();
        System.out.println(singleResult);
    }

    /**
     * HQL分页
     */
    @Test
    public void testList9() {
        Query query = session.createQuery("from Book");
        query.setFirstResult(2);
        query.setMaxResults(3);
        List<Book> list = query.list();
        for (Book b : list) {
            System.out.println(b);
        }
    }
}
BaseDao: 
package com.hxc.five.util;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.hibernate.Session;
import org.hibernate.query.Query;

/**
 * hibernate的通用查询Dao层
 *  思想完全借鉴于sql的BaseDao sql= select * from t_mvc_book where bname like ‘%圣墟%‘
 *  countSql=select cout(1) from (sql) t;
 *  pageSql=sql limit start,offset
 *
 *
 *    hql:
 *     hql= select * from Book where bookName like :bookName
 *      hql=from book where bookName like :bookName
 *     思想:将原生的hql语句以from关键字进行截取
 *  countHql=select count(*) from Book where bookName like : bookName:
 *  pageeHql不需要写,因为hibernate已经封装了内置分页接口 getFirstResult getMaxResult
 *
 * @author 旧城
 *
 */
public class BaseDao {

    /**
     * 给hibernate中的query对象中的命名参数列表赋值
     * @param query
     * @param map
     */
    public void setParam(Query query, Map<String, Object> map) {
        if (map != null && map.size() > 0) {
            Set<Entry<String, Object>> entrySet = map.entrySet();
            for (Entry<String, Object> entry : entrySet) {
                Object value=entry.getValue();
                if(value instanceof Collection) {
                    query.setParameter(entry.getKey(), (Collection)value);
                }else if(value instanceof Object[]){
                    query.setParameter(entry.getKey(), (Object[])value);
                }else {
                    query.setParameter(entry.getKey(), value);
                }
            }
        }
    }
    /**
     * hql= select * from Book where bookName like :bookName
     *      hql=from book where bookName like :bookName
     *     思想:将原生的hql语句以from关键字进行截取
     *  countHql=select count(*) from Book where bookName like : bookName:
     *
     * @param hql
     * @return
     */
    public String  getCountHql(String hql) {
        return "select count(*) "+ hql.substring(hql.toUpperCase().indexOf("FROM"));
    }

    /**
     * 通用hql语句查询
     * @param session        当前会话
     * @param hql            带参数的hql语句
     * @param map            命名参数对应的值的集合
     * @param pageBean        分页实体类
     * @return
     */
    public List executeQuery(Session session,String hql,Map<String , Object> map,PageBean pageBean) {
         List list=null;
            Query query=null;
            if(pageBean!=null&&pageBean.isPagination()) {
                String countHql = getCountHql(hql);
                Query createQuery = session.createQuery(countHql);
                this.setParam(createQuery, map);
                pageBean.setTotal(createQuery.getSingleResult().toString());
                 query = session.createQuery(hql);
                    this.setParam(query, map);
                    query.setFirstResult(pageBean.getStartIndex());
                    query.setMaxResults(pageBean.getRows());
                    list=query.list();
            }else {
                 query = session.createQuery(hql);
                    this.setParam(query, map);
                list=query.list();
            }
            return list;
    }
}
BookDao 
package com.hxc.four.dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;

import com.hxc.five.util.BaseDao;
import com.hxc.five.util.PageBean;
import com.hxc.five.util.StringUtils;
import com.hxc.four.entity.Book;
import com.hxc.four.entity.Category;
import com.hxc.two.util.SessionFactoryUtils;

public class BookDao extends BaseDao{
    public Integer addBook(Book book) {
        Session session = SessionFactoryUtils.openSession();
        Transaction transaction = session.beginTransaction();
        Integer bid = (Integer) session.save(book);
        transaction.commit();
        session.close();
        return bid;
    }

    public Integer addCategory(Category category) {
        Session session = SessionFactoryUtils.openSession();
        Transaction transaction = session.beginTransaction();
        Integer cid = (Integer) session.save(category);
        transaction.commit();
        session.close();
        return cid;
    }

    public Category getCategory(Category category) {
        Session session = SessionFactoryUtils.openSession();
        Transaction transaction = session.beginTransaction();
        Category c = session.get(Category.class, category.getCategoryId());
        transaction.commit();
        session.close();
        return c;
    }

    public Book getBook(Book book) {
        Session session = SessionFactoryUtils.openSession();
        Transaction transaction = session.beginTransaction();
        Book b = session.get(Book.class, book.getBookId());
        if (b != null && new Integer(1).equals(book.getInitCategories())) {
            Hibernate.initialize(b.getCategories());
        }
        transaction.commit();
        session.close();
        return b;
    }

    public void delBook(Book book) {
        Session session = SessionFactoryUtils.openSession();
        Transaction transaction = session.beginTransaction();
        session.delete(book);
        transaction.commit();
        session.close();
    }

    public void delCategory(Category category) {
        Session session = SessionFactoryUtils.openSession();
        Transaction transaction = session.beginTransaction();
        Category c = session.get(Category.class, category.getCategoryId());
        if (c != null) {
            for (Book b : c.getBooks()) {
                // 通过在被控方通过主控方来解除关联关系,最后被控方再做删除
                b.getCategories().remove(c);
            }
        }
        session.delete(c);
        transaction.commit();
        session.close();
    }

    /********************** 通用查询 **************************/
    public List<Book> list1(Book book, PageBean pageBean) {
        Session session = SessionFactoryUtils.openSession();
        Transaction transaction = session.beginTransaction();

        // 下面代码处理的是book实体类的条件查询
        String bookName = book.getBookName();

        // sql语句where后面可以直接写true,而hql不能出现true
        String hql = "from Book where 1=1";
        if (StringUtils.isNotBlank(bookName)) {
            hql += " and bookName like :bookName";
        }
        Query query = session.createQuery(hql);
        if (StringUtils.isNotBlank(bookName)) {
            query.setParameter("bookName", bookName);
        }

        // 处理的是分页
        if (pageBean != null && pageBean.isPagination()) {
            query.setFirstResult(pageBean.getStartIndex());
            query.setMaxResults(pageBean.getRows());
        }
        List list = query.list();

        transaction.commit();
        session.close();
        return list;

    }

    public List<Book> list2(Book book, PageBean pageBean) {
         Session session=SessionFactoryUtils.openSession();
            Transaction transaction=session.beginTransaction();
            //下面代码处理的是book实体类的条件查询 10*2
            String bookName=book.getBookName();
            Map<String,Object> map=new HashMap<String,Object>();
            //sql语句where后面可以直接写true,而hql与不能出现true
            String hql="from Book where 1=1";
            if(StringUtils.isNotBlank(bookName)) {
                hql+=" and bookName like :bookName";

                map.put("bookName",bookName);
            }
            List list=super.executeQuery(session, hql, map, pageBean);
            transaction.commit();
            session.close();
            return list;
        }
}
BookDaoTest 
package com.hxc.four.dao;

import java.util.List;

import org.junit.Test;

import com.hxc.five.util.PageBean;
import com.hxc.four.entity.Book;
import com.hxc.four.entity.Category;

public class BookDaoTest {
    private BookDao bookDao = new BookDao();

    @Test
    public void testGetBook() {
        Book book = new Book();
        book.setBookId(8);
        book.setInitCategories(1);
        Book b = this.bookDao.getBook(book );
        System.out.println(b.getBookName());
        System.out.println(b.getCategories());
    }

    /**
     * book.hbm.xml    inverse=fasle
     * category.hbm.xml inverse=true
     * 数据添加正常
     * 书籍表、桥接表各新增一条数据
     */
    @Test
    public void test1() {
        Book book = new Book();
        book.setBookName("旧城");
        book.setPrice(10f);
        Category category = new Category();
        category.setCategoryId(5);
//        直接将category对象加入到新建的book中是错误的,因为此时的category是临时态的,hibernate是不会管理的
//        book.getCategories().add(category);
        Category c = this.bookDao.getCategory(category);

//        c.getBooks().add(book);
        book.getCategories().add(c);
        this.bookDao.addBook(book);
    }

    /**
     * book.hbm.xml    inverse=false
     * category.hbm.xml inverse=true
     * 只增加书籍表数据
     * 桥接表不加数据
     * 原因:双方都没有去维护关系
     */
    @Test
    public void test2() {
        Book book = new Book();
        book.setBookName("c");
        book.setPrice(10f);
        Category category = new Category();
        category.setCategoryId(5);
        Category c = this.bookDao.getCategory(category);

        book.getCategories().add(c);
        this.bookDao.addBook(book);
//        c.getBooks().add(book);
    }

    @Test
    public void testList1() {
        Book book=new Book();
//        book.setBookName("%旧城%");
        PageBean pageBean=new PageBean();
        pageBean.setPage(2);
        List<Book> list1=this.bookDao.list1(book, pageBean);
        for (Book b : list1) {
            System.out.println(b);
        }

    }

    @Test
    public void testList2() {
        Book book=new Book();
//        book.setBookName("%旧城%");
        PageBean pageBean=new PageBean();
        pageBean.setPage(2);
        List<Book> list1=this.bookDao.list2(book, pageBean);
        for (Book b : list1) {
            System.out.println(b);
        }
    }    

}
testList1运行结果:
testList1运行结果:

原文地址:https://www.cnblogs.com/huxiaocong/p/11324519.html

时间: 2024-10-08 18:09:04

hibernate之HQL语句的相关文章

hibernate 之 HQL语句总结【转】

1. 查询整个映射对象所有字段 //直接from查询出来的是一个映射对象,即:查询整个映射对象所有字段 String hql = "from Users"; Query query = session.createQuery(hql); List<Users> users = query.list(); for(Users user : users){ System.out.println(user.getName() + " : " + user.ge

Hibernate写hql语句与不写hql语句的区别?

写hql语句与不写hql语句的区别? 写hql语句:书写HQL语句,所有的查询与投影的设计均使用HQL语句完成. 不写hql语句:没有任何查询语句,所有的查询与投影的设计使用面向对象格式完成. 二者选用的时机: 不写hql语句,有时比较方便,在不考虑复杂的查询的情况下,可以使用,此方法把某些Hibernate的方法封装起来,不灵活. 写hql语句,复杂的业务逻辑,建议使用,灵活方便. 以下通过俩种方法的对比来着重介绍一下hibernate不写hql的一种简单用法. 写hql语句: 具有丰富的灵活

Hibernate 的HQL语句,初级

这里讲解简单的HQL语句,因为很多比较复杂的外查询,用一般的查询很难完成 所以这里需要使用HQL @Test public void selquery(){ System.out.printf("hello"); Configuration config = new Configuration(); SessionFactory sessionfactory = config.configure("hibernate.cfg.xml").buildSessionFa

关于hibernate中hql语句 case when的写法

java hql case when的用法 if(null == sorter){ hql.append(" order by m.mDate desc,case when m.mealTime = 'morning' then '1' when m.mealTime = 'noon' then '2' when m.mealTime = 'night' then '3' when m.mealTime = 'midnight' then '4' end "); } 注: 上面hql语

怎样在hibernate的HQL语句中使用mysql 的自定义函数?

问题:怎样在hibernate中使用mysql的函数? 1.hibernate支持原生态的sql语句查询,使用session.createSQLQuery()创建查询对象: 2.怎样在hql中使用mysql函数呢? 这时就需要重新定义hibernate的方言(dialect),将你需要用到的进行注册:  这里提到一个方言(dialect)的概念: Hibernate底层依然使用SQL语句来执行数据库操作,虽然所有关系型数据库都支持使用标准SQL语句,但所有数据库都对标准SQL进行了一些扩展,所以

hibernate中hql语句中list和iterate区别

1.使用list()方法获取查询结果,每次发出一条语句,获取全部数据.2.使用iterate()方法获取查询结果,先发出一条SQL语句用来查询满足条件数据的id,然后依次按照这些id查询记录,也就是要执行N+1条SQL语句(N为符合条件的记录数) 两次执行list()方法,每次执行都是发出一条SQL语句,查询所有数据.下面看看两次执行iterate()方法的输出情况两次执行iterate()方法,第一次执行时发出了N+1条SQL语句,而第二次执行,则只发出一套SQL语句,与先执行list()方法

Hibernate的HQL语句中定位参数和具名参数传参

HQL查询: 1.有关hql 查询语句中的问好参数形式,如果出现多个问号,这对后面参数就比较麻烦. 如:from Student  student where student.name = ? and student.age=?.... 对这样的赋值,容易出错 可以采用另一种赋值的方法 如:from Student  student where student.name =:var1 and student.age=:var2.... query.setString("var1",&q

Hibernate中HQL语句中list与iterate区别

session.createQuery("from Classes").list() session.createQuery("from Classes").iterate(); 这两者有什么区别    *  发出sql语句的不同    *  利用缓存的不同

hibernate的hql语句不支持 count(case...when ....else..)?

查看帖子:http://www.iteye.com/problems/4499 第一次这么写, 不行, 关键就是: 同是聚集函数,sum 就OK, 而 count 就不行...........后来还是改用了sql语句, 还是sql轻便... 原文地址:https://www.cnblogs.com/yadongliang/p/9657789.html