技术开发 频道

Castle ActiveRecord学习实践(7):使用HQL查询


【IT168技术文档】

  摘要:虽然ActiveRecord为我们提供了Find()和FindAll()这样两个静态的查询方法,并且有Where特性可供使用,但是仍然不能解决实际开发中一些复杂的查询,这时我们就需要通过HQL查询来实现。



  主要内容

  1.HQL概述

  2.SimpleQuery查询

  3.ScalarQuery查询

  4.自定义查询

  5.使用CallBack



  一.HQL简单介绍

  HQL全名是Hibernate Query Language,它是一种完全面向对象的查询语言。先来看一下HQL最基本的一些用法
1.From子句 from Post 你也可以为Post起一个别名 from Post as post 或者省略as from Post post 2Select 子句 select Name,Author from Blog 也可以使用elements函数来查询一个集合 select elements(blog.Posts) from Blog blog 3.使用聚合函数 HQL中也可以使用一些聚合函数 select count(*) from Blog blog select count(elements(blog.Posts)) from Blog blog HQL支持的聚合函数有 avg(), sum(), min(), max() count(*) count(), count(distinct ), count(all) 4.Where子句 from Blog blog where blog.Name = ‘Terry Lee’ from Blog blog where blog.Name is not null
  二.SimpleQuery查询

  SimpleQuery是一种最简单的查询,它直接处理HQL语句,并返回一个集合,没有复杂的参数处理。具体用法可以参考下例:
[ActiveRecord("Posts")] public class Post : ActiveRecordBase { // /**//// <summary> /// 查询某一类别的所有Posts /// </summary> /// <param name="_strCategory">类别名称</param> /// <returns></returns> public static Post[] GetPostsByCategory(string _strCategory) { SimpleQuery query = new SimpleQuery( typeof(Post), @"from Post post where post.Category = ?", _strCategory ); return (Post[])ExecuteQuery(query); } /**//// <summary> /// 查询某一时间段内发表的所有Posts /// </summary> /// <param name="start">开始时间</param> /// <param name="end">结束时间</param> /// <returns></returns> public static int[] GetPostsInterval(DateTime start,DateTime end) { SimpleQuery query = new SimpleQuery( typeof(Post),typeof(int), @"select post.Id from Post post where post.Created between ? and ?", start,end ); return (int[])ExecuteQuery(query); } }
0
相关文章