我碰到、想到和回答过的NHibernate里的不能单独成文的小知识点,持续更新。
Q:不设置Cache时NHibernate会使用二级缓存吗
A:会,它会使用NHibernate.Cache.HashtableCacheProvider
Q:配置文件中use_outer_join和max_fetch_depth有什么作用
A:当使用关联影射时,如果未设置延迟加载,如果use_outer_join为true,则NHibernate用带join的Sql同时读取对象;为false,则分两条Sql读取。
max_fetch_depth表示最多join几个对象。
Q:查询时如何分页
A:使用ICriteria时
ISession session=factory.OpenSession();
ICriteria criteria=session.CreateCriteria(typeof(News));
criteria.SetFirstResult(fromResult);
criteria.SetMaxResults(count);
return criteria.List();
使用IQuery时
IQuery query = Session.CreateQuery(hql);
query.SetFirstResult(fromResult);
query.SetMaxResults(count);
return query.List();
SetFirstResult设置从那天记录开始,SetMaxResults设置取几条数据
Q:Sql2005有dialect吗
A:有,NHibernate论坛可以找到,单独的文件,以后版本可能会加入NHibernate内部。
MsSql2005Dialect.
using System.Text;
using NHibernate.SqlCommand;
namespace NHibernate.Dialect
{
public class MsSql2005Dialect : MsSql2000Dialect
{
public override SqlString GetLimitString(SqlString querySqlString, int offset, int last)
{
/**//*
* WITH query AS
* (SELECT TOP last ROW_NUMBER() OVER (ORDER BY orderby) as __hibernate_row_nr__, original_query)
* SELECT *
* FROM query
* WHERE __hibernate_row_nr__ > offset
* ORDER BY __hibernate_row_nr__
*/
SqlStringBuilder pagingBuilder = new SqlStringBuilder();
StringBuilder orderByStringBuilder = new StringBuilder();
string distinctStr = string.Empty;
foreach (object sqlPart in querySqlString.SqlParts)
{
string sqlPartString = sqlPart as string;
if (sqlPartString != null)
{
string loweredString = sqlPartString.ToLower();
int orderByIndex = loweredString.IndexOf("order by");
if (orderByIndex != -1)
{
// if we find a new "order by" then we need to ignore
// the previous one since it was probably used for a subquery
orderByStringBuilder = new StringBuilder();
orderByStringBuilder.Append(sqlPartString.Substring(orderByIndex));
}
if (loweredString.TrimStart().StartsWith("select"))
{
int index = 6;
if (loweredString.StartsWith("select distinct"))
{
distinctStr = "DISTINCT ";
index = 15;
}
sqlPartString = sqlPartString.Substring(index);
}
pagingBuilder.Add(sqlPartString);
}
else
{
pagingBuilder.AddObject(sqlPart);
}
}
string orderby = orderByStringBuilder.ToString();
// if no ORDER BY is specified use fake ORDER BY field to avoid errors
if (orderby == null || orderby.Length == 0)
orderby = "ORDER BY CURRENT_TIMESTAMP";
string beginning =
string.Format("WITH query AS (SELECT {0}TOP {1} ROW_NUMBER() OVER ({2}) as __hibernate_row_nr__, ",
distinctStr, last, orderby);
string ending =
string.Format(") SELECT * FROM query WHERE __hibernate_row_nr__ > {0} ORDER BY __hibernate_row_nr__",
offset);
pagingBuilder.Insert(0, beginning);
pagingBuilder.Add(ending);
return pagingBuilder.ToSqlString();
}
public override bool SupportsLimit
{
get { return true; }
}
public override bool SupportsLimitOffset
{
get { return true; }
}
}
}
Q:Access有dialect吗
A:NHibernateContrib里面有NHibernate.JetDriver.JetDialect
Q:Guid的unsaved-value怎么设置
A:unsaved-value="00000000-0000-0000-0000-000000000000"