/// <summary>
/// 泛型搜索 - DISTINCT
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="field">列名,用","分开,不带别名</param>
/// <param name="where"></param>
/// <param name="alias">别名</param>
#region IList<T> SearchDistinct<T>(string where,string field,string alias)
public IList<T> SearchDistinct<T>(string where, string field, string alias)
{
try
{
//有意思的模板反射哟~
T obj = (T)System.Reflection.Assembly.GetAssembly(typeof(T)).CreateInstance(typeof(T).ToString());
// 反射DTO对象的各字段,必须把字段和DB中字段同名
System.Reflection.PropertyInfo[] pps = obj.GetType().GetProperties();
//拆分成别名+列名
string[] cols = field.Split(',');
string columns = string.Empty;
foreach (string col in cols)
columns += string.Format("{0}.{1},", alias, col);
columns = columns.TrimEnd(',');
//hql
string hql = string.Format("select distinct {2} from {0} {3} {1}",
obj.GetType().ToString(),
where.ToUpper().StartsWith("WHERE") ? where : "WHERE " + where
, columns
, alias);
IList alist = HibernateTemplate.Find(hql);
IList<T> list = new List<T>();
if (alist != null && alist.Count > 0)
{
//是否为数组
bool isArray = (cols.Length == 1 ? false : true);
foreach (object arr in alist)
{
//产生一个类实例
T t = (T)System.Reflection.Assembly.GetAssembly(typeof(T)).CreateInstance(typeof(T).ToString());
for (int i = 0; i < cols.Length; i++)
{
foreach (System.Reflection.PropertyInfo pi in pps)
{
if(pi.Name.Equals(cols[i]))
{
//数组与object对象
pi.SetValue(t, (isArray ? (arr as object[])[i] : arr), null);
}
}
}
list.Add(t);
}
return list;
}
else
return null;
}
catch (Exception ex)
{
ILog log = LogManager.GetLogger(typeof(T));
log.Error(ex.Message, ex);
return null;
}
}
#endregion
/// <summary>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="where"></param>
/// <param name="propertyName"></param>
/// <param name="ascending"></param>
#region IList<T> SearchWithOrder<T>(string where, string propertyName, bool ascending)
public IList<T> SearchWithOrder<T>(string where, string propertyName, bool ascending)
{
try
{
//排序
Order order = new Order(propertyName, ascending);
//排序
ICriteria ic = Session.CreateCriteria(typeof(T));
ic.AddOrder(order);
//表达式
ICriterion exp = Expression.Sql(where);
ic.Add(exp);
return ic.List<T>();
}
catch (Exception ex)
{
ILog log = LogManager.GetLogger(typeof(T));
log.Error(ex.Message, ex);
return null;
}
}

浙公网安备 33010602011771号