【Hibernate】Hibernate查询语言HQL详解
生活随笔
收集整理的這篇文章主要介紹了
【Hibernate】Hibernate查询语言HQL详解
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
常用的HQL語句
HQL: Hibernate Query Language.
特點:
1,與SQL相似,SQL中的語法基本上都可以直接使用。
2,SQL查詢的是表和表中的列;HQL查詢的是對象與對象中的屬性。
3,HQL的關鍵字不區分大小寫,類名與屬性名是區分大小寫的。
4,SELECT可以省略.
1,簡單的查詢
Employee為實體名而不是數據庫中的表名(面向對象特性)
hql = "FROM Employee"; hql = "FROM Employee AS e"; // 使用別名 hql = "FROM Employee e"; // 使用別名,as關鍵字可省略2,帶上過濾條件的(可以使用別名):Where
hql = "FROM Employee WHERE id<10"; hql = "FROM Employee e WHERE e.id<10"; hql = "FROM Employee e WHERE e.id<10 AND e.id>5";3,帶上排序條件的:Order By
hql = "FROM Employee e WHERE e.id<10 ORDER BY e.name"; hql = "FROM Employee e WHERE e.id<10 ORDER BY e.name DESC"; hql = "FROM Employee e WHERE e.id<10 ORDER BY e.name DESC, id ASC";4,指定select子句(不可以使用select *)
hql = "SELECT e FROM Employee e"; // 相當于"FROM Employee e" hql = "SELECT e.name FROM Employee e"; // 只查詢一個列,返回的集合的元素類型就是這個屬性的類型 hql = "SELECT e.id,e.name FROM Employee e"; // 查詢多個列,返回的集合的元素類型是Object數組 hql = "SELECT new Employee(e.id,e.name) FROM Employee e"; // 可以使用new語法,指定把查詢出的部分屬性封裝到對象中5,執行查詢
獲得結果(list、uniqueResult、分頁 )
Query query = session.createQuery("FROM Employee e WHERE id<3"); query.setFirstResult(0); query.setMaxResults(10); // 等同于 limit 0,10 兩種查詢結果list、uniqueResultList list = query.list(); // 查詢的結果是一個List集合 Employee employee = (Employee) query.uniqueResult();// 查詢的結果是唯一的一個結果,當結果有多個,就會拋異常6,方法鏈
List list = session.createQuery("FROM Employee e").setFirstResult(0).setMaxResults(10).list();7,聚集函數
count(), max(), min(), avg(), sum()
hql = "SELECT COUNT(*) FROM Employee"; // 返回的結果是Long型的 hql = "SELECT min(id) FROM Employee"; // 返回的結果是id屬性的類型8,分組: Group By … Having
hql = "SELECT e.name,COUNT(e.id) FROM Employee e GROUP BY e.name"; hql = "SELECT e.name,COUNT(e.id) FROM Employee e GROUP BY e.name HAVING count(e.id)>1"; hql = "SELECT e.name,COUNT(e.id) FROM Employee e WHERE id<9 GROUP BY e.name HAVING count(e.id)>1"; hql = "SELECT e.name,COUNT(e.id) " + "FROM Employee e " + "WHERE id<9 " + "GROUP BY e.name " + "HAVING count(e.id)>1 " + "ORDER BY count(e.id) ASC"; hql = "SELECT e.name,COUNT(e.id) AS c " + "FROM Employee e " + "WHERE id<9 " + "GROUP BY e.name " + "HAVING count(e.id)>1 " + // 在having子句中不能使用列別名"ORDER BY c ASC"; // 在orderby子句中可以使用列別名9,連接查詢
HQL是面向對象的查詢
內連接(inner關鍵字可以省略)
hql = "SELECT e.id,e.name,d.name FROM Employee e JOIN e.department d";hql = "SELECT e.id,e.name,d.name FROM Employee e INNER JOIN e.department d";左外連接(outer關鍵字可以省略)
hql = "SELECT e.id,e.name,d.name FROM Employee e LEFT OUTER JOIN e.department d";右外連接(outer關鍵字可以省略)
hql = "SELECT e.id,e.name,d.name FROM Employee e RIGHT JOIN e.department d";//可以使用更方便的方法hql = "SELECT e.id,e.name,e.department.name FROM Employee e";10,查詢時使用參數
方式一:使用’?’占位
hql = "FROM Employee e WHERE id BETWEEN ? AND ?";List list2 = session.createQuery(hql).setParameter(0, 5)// 設置參數,第1個參數的索引為0。.setParameter(1, 15).list();方式二:使用變量名
hql = "FROM Employee e WHERE id BETWEEN :idMin AND :idMax";List list3 = session.createQuery(hql).setParameter("idMax", 15).setParameter("idMin", 5).list();// 當參數是集合時,一定要使用setParameterList()設置參數值hql = "FROM Employee e WHERE id IN (:ids)";List list4 = session.createQuery(hql).setParameterList("ids", new Object[] { 1, 2, 3, 5, 8, 100 }).list();11,update與delete,不會通知Session緩存
Update
int result = session.createQuery("UPDATE Employee e SET e.name=? WHERE id>15").setParameter(0, "無名氏").executeUpdate(); // 返回int型的結果,表示影響了多少行。Delete
int result1 = session.createQuery(//"DELETE FROM Employee e WHERE id>15").executeUpdate(); // 返回int型的結果,表示影響了多少行。工具類:將HQL語句轉換為SQL語句
/** * 將hql 語句轉換為sql語句 * @param hql 要轉換的 hql語句 */ public String transHqlToSql(String hql){SessionFactoryImpl sfi = (SessionFactoryImpl)awMixThrProDao.getSessionD().getSessionFactory();QueryTranslatorFactory qtf = sfi.getSettings().getQueryTranslatorFactory();FilterTranslator qt = qtf.createFilterTranslator(hql, hql, null, sfi);qt.compile( null, false );System. out.println(" hql==>sql: " +qt.getSQLString());return qt.getSQLString(); }HQL生成工具類
/*** 根據實體構建hql 語句* @author lxl* @createTime 2013-05 -10 16:00* @version 1.0*/ public class BuildHqlUtil {/*** 根據實體生成對應的hql語句,對象中具有值的屬性將成為查詢的限制條件部分<br/>* 其中,對于String類型的屬性是 like 判斷的,以其開頭的:like '[value]%'* @param entity* @return*/@SuppressWarnings( "unchecked")public static String buildSelectStr(Object entity) {return buildSelectStr(entity, null);}/*** 根據實體生成有字段限制的 hql語句,對象中具有值的屬性將成為查詢的限制條件部分<br/>* 其中,對于String類型的屬性是 like 判斷的,以其開頭的:like '[value]%'* @param entity* @param queryFields 數組形式的查詢字段:select xxx,xxx ...* @return*/@SuppressWarnings( "unchecked")public static String buildSelectStr(Object entity, String[] queryFields) {if (entity == null) {try {throw new Exception("實體不能為null");} catch (Exception e) {e.printStackTrace();return null ;}}Class clazz = entity.getClass();String hqlStr = "";try {Field[] fields = clazz.getDeclaredFields();Field.setAccessible(fields, true);hqlStr = getFieldMsg(fields, queryFields) + getWhereMsg(entity, fields, queryFields);} catch (Exception e) {e.printStackTrace();}return hqlStr;}/*** 構建查詢字段* @param fields* @param queryFields* @return* @throws Exception*/private static String getFieldMsg(Field[] fields, String[] queryFields)throws Exception {String selectStr = "";int i, j;if (queryFields != null && queryFields.length != 0) {selectStr = "select ";for (i = 0; i < queryFields.length ; i++) {if (!"" .equals(queryFields[i])) {boolean flag = false;for (j = 0; j < fields.length; j++) {if (queryFields[i].equals(fields[j].getName())) {flag = true;}}if (flag) {selectStr += queryFields[i] + ",";} else {throw new Exception("實體中不存在該字段:" + queryFields[i]);}}}if ("select " .equals(selectStr)) {selectStr = "";} else {selectStr = selectStr.substring(0, selectStr.length() - 1)+ " ";}}return selectStr;}/*** 構建查詢條件** @param entity* @param fields* @param queryFields* @return* @throws IllegalArgumentException* @throws IllegalAccessException*/private static String getWhereMsg(Object entity, Field[] fields, String[] queryFields)throws IllegalArgumentException, IllegalAccessException {String whereStr = "from " + entity.getClass().getSimpleName() + " where 1=1";for (int i = 0; i < fields.length; i++) {if (fields[i].get(entity) == null || fields[i].get(entity).toString().trim().length() == 0) {continue;}String value = fields[i].get(entity).toString();String field = fields[i].getName();if (isNum(fields[i].getType().getName())) {whereStr += " and " + field + "=" + value;} else {whereStr += " and " + field + " like '" + value + "%'";}}return whereStr;}/*** 判斷是否為Integer,Double,Float等數字類型,注意都是封裝類型* @param fieldName* @return*/private static boolean isNum(String fieldName) {boolean flag = false;if (fieldName.endsWith(".Integer" )|| fieldName.endsWith( ".Double")|| fieldName.endsWith( ".Float")|| fieldName.endsWith( ".Long")|| fieldName.endsWith( ".Number")|| fieldName.endsWith( ".BigDecimal")) {flag = true;}return flag;}}一點注意
關于Hibernate執行帶有join的HQL語句:
Query query = session.createQuery("select c from Custom as c join c.orders as ord where ord.name = : name"); query.setString("name", "1213233"); List list = query.list(); for(int i=0;i<list.size();i++){Custom custom = (Custom)list.get(i); }總結
以上是生活随笔為你收集整理的【Hibernate】Hibernate查询语言HQL详解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Hibernate】Hibernate
- 下一篇: 人才招聘网站